How to send email from a JAVA programs

  • If using JDK6 and higher only mail.jar needs to be in your classpath
  • CLASSPATH settings: setenv CLASSPATH .:/home/helmut/JAVAVM/MAIL/javamail-1.4.7/mail.jar
  • Check your eamil program  ( like Thunderbird ) to ge info about smtp hostname, portnumbers, SSL in use ,,, and change the JAVA code below
  • Compile : javac
  • Run it: : javac SendMailSSL.javaRun it:
  • Note : remove    props.put(“mail.debug”, “true”);  to suppress JAVA Mail debug messages : 

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailSSL 
        public static void main(String[] args) 
                String s = run_it();
        System.out.println("Status: " + s );
        public static String run_it()
                Properties props = new Properties();
                props.put("mail.debug", "true");
                props.put("", "");
                props.put("mail.smtp.socketFactory.port", "465");
                props.put("mail.smtp.socketFactory.class", "");
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.port", "465");

                Session session = Session.getDefaultInstance(props,
                        new javax.mail.Authenticator() {
                                protected PasswordAuthentication getPasswordAuthentication() {
                                        return new PasswordAuthentication("","111margit");

                try {

                        Message message = new MimeMessage(session);
                        message.setFrom(new InternetAddress(""));
                        message.setSubject("Testing Subject");
                        message.setText("Dear Mail Crawler," +
                                        "\n\n No spam to my email, please!");


            return("Mail sent"); 
                } catch (MessagingException e) {
                        throw new RuntimeException(e);

Leave a Reply

Your email address will not be published. Required fields are marked *