How do I send email using Gmail via TLS?

The following example show you how to send email using Gmail SMTP via TLS connection. The username and password is use to authenticate you against the Gmail.

The configuration / properties used for connection to the Gmail SMTP is defined in the createConfiguration() method. The properties include information such as the SMTP host address, port number, etc.

Let’s see the code snippet below:

package org.kodejava.example.mail;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class GmailSendEmailTLS {
    public static void main(String[] args) throws Exception {
        GmailSendEmailTLS demo = new GmailSendEmailTLS();
        demo.sendMail("[email protected]", "[email protected]",
                "TLS - Gmail Send Email Demo",
                "TLS - Gmail Send Email Demo");
    }

    private void sendMail(String mailFrom, String mailTo,
                          String mailSubject, String mailText)
            throws Exception {

        Properties config = createConfiguration();
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("username", "password");
            }
        };

        // Creates a mail session. We need to supply username and
        // password for Gmail authentication.
        Session session = Session.getInstance(config, authenticator);

        // Creates email message
        Message message = new MimeMessage(session);
        message.setSentDate(new Date());
        message.setFrom(new InternetAddress(mailFrom));
        message.setRecipient(Message.RecipientType.TO,
                new InternetAddress(mailTo));
        message.setSubject(mailSubject);
        message.setText(mailText);

        // Send a message
        Transport.send(message);
    }

    private Properties createConfiguration() {
        return new Properties() {{
            put("mail.smtp.auth", "true");
            put("mail.smtp.host", "smtp.gmail.com");
            put("mail.smtp.port", "587");
            put("mail.smtp.starttls.enable", "true");
        }};
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

1 Comments

Leave a Reply