Send SSL encoded Email from Java

Table of Contents

Build Steps

  • Download javax.mail.jar 1.6.x from : https://javaee.github.io/javamail/
  • Compile Code: # javac -cp ./javax.mail.jar:. testEmail.java
  • Run Code : # java -cp ./javax.mail.jar:. testEmail

Java Code

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


public class testEmail {

    public static void main(String[] args) {
        testEmail.sendEmail();
    }

    public static void sendEmail() {

        Properties props = new Properties();
        props.put("mail.smtp.host", "my.ohmportal.de");
        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("xxxxx", "xxxx");
                    }
                });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("xxxxr@th-nuernberg.de"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("xxxx@gmail.com"));
            message.setSubject("This is testing message");
            message.setText("Hi this is testing email....not spam");

            Transport.send(message);
            System.out.println("email successfully sent..");

        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}