Send_email_via_JAVA

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 SendMailSSL.java
  • Run it: : javac SendMailSSL.javaRun it:
  • Note : remove    props.put(“mail.debug”, “true”);  to suppress JAVA Mail debug messages

SendMailSSL.java : 

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("mail.smtp.host", "stbeehive.oracle.com");
                props.put("mail.smtp.socketFactory.port", "465");
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                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("Helmut.Hutzler@oracle.com","111margit");
                                }
                        });

                try {

                        Message message = new MimeMessage(session);
                        message.setFrom(new InternetAddress("Helmut.Hutzler@oracle.com"));
                        message.setRecipients(Message.RecipientType.TO,
                                        InternetAddress.parse("Helmut.Hutzler@oracle.com"));
                        message.setSubject("Testing Subject");
                        message.setText("Dear Mail Crawler," +
                                        "\n\n No spam to my email, please!");

                        Transport.send(message);

                        System.out.println("Done");
            return("Mail sent"); 
                } catch (MessagingException e) {
                        throw new RuntimeException(e);
                }
        }
}

Leave a Reply

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