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 used 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.

To send email using Gmail via SSL see the following code snippet How do I send email using Gmail via SSL?.

Let’s see the code snippet below:

package org.kodejava.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 {
    private static final String USERNAME = "kodejava@gmail.com";
    private static final String PASSWORD = "password";

    public static void main(String[] args) throws Exception {
        // Email information such as from, to, subject and contents.
        String mailFrom = "kodejava@gmail.com";
        String mailTo = "kodejava@gmail.com";
        String mailSubject = "TLS - Gmail Send Email Demo";
        String mailText = "TLS - Gmail Send Email Demo";

        GmailSendEmailTLS gmail = new GmailSendEmailTLS();
        gmail.sendMail(mailFrom, mailTo, mailSubject, mailText);
    }

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

        Properties config = createConfiguration();

        // Creates a mail session. We need to supply username and
        // password for Gmail authentication.
        Session session = Session.getInstance(config, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                        GmailSendEmailTLS.USERNAME,
                        GmailSendEmailTLS.PASSWORD
                );
            }
        });

        // 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");
            put("mail.smtp.ssl.protocols", "TLSv1.2");
        }};
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I send email using Gmail via SSL?

In another example you’ve seen how to send email using Gmail SMTP via TLS. See the following example How do I send email using Gmail via TLS?.

In this example you will use the SSL connection to connect to Gmail SMTP server. The difference with this is in the properties / configuration that we used to create the mail session object.

package org.kodejava.mail;

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

public class GmailSendEmailSSL {
    private static final String USERNAME = "kodejava@gmail.com";
    private static final String PASSWORD = "password";

    public static void main(String[] args) throws Exception {
        // Email information such as from, to, subject and contents.
        String mailFrom = "kodejava@gmail.com";
        String mailTo = "kodejava@gmail.com";
        String mailSubject = "SSL - Gmail Send Email Demo";
        String mailText = "SSL - Gmail Send Email Demo";

        GmailSendEmailSSL gmail = new GmailSendEmailSSL();
        gmail.sendMail(mailFrom, mailTo, mailSubject, mailText);
    }

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

        Properties config = createConfiguration();

        // Creates a mail session. We need to supply username and
        // password for Gmail authentication.
        Session session = Session.getInstance(config, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                        GmailSendEmailSSL.USERNAME,
                        GmailSendEmailSSL.PASSWORD
                );
            }
        });

        // 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.host", "smtp.gmail.com");
            put("mail.smtp.auth", "true");
            put("mail.smtp.port", "465");
            put("mail.smtp.socketFactory.port", "465");
            put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            put("mail.smtp.ssl.protocols", "TLSv1.2");
        }};
    }
}

There is a chance that you can get an error that tell you cannot connect to the smtp.gmail.com port 465. If this is the case please check your connection to the server using telnet command. The command is telnet smtp.gmail.com 465, and see if there is a reply.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I debug application that uses JavaMail APIs?

To ask Java mail to print out a debug message when you run a Java mail program you can add the mail.debug and set the value to true into the properties used to create the session object.

The other way is to set the debug setting of the session using the session.setDebug() method and pass true as the parameter. This will also turn on the debug message in your Java mail program.

package org.kodejava.mail;

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

public class MailDebugDemo {
    public static void main(String[] args) {
        MailDebugDemo.sendMail("kodejava@gmail.com", "kodejava@gmail.com",
                "Debug Demo", "Mail Debug Demo");
    }

    private static void sendMail(String mailFrom, String mailTo, String mailSubject,
                                 String mailText) {
        Properties props = new Properties() {{
            put("mail.smtp.auth", "true");
            put("mail.smtp.host", "smtp.gmail.com");
            put("mail.transport.protocol", "smtp");
            put("mail.smtp.port", "587");
            put("mail.smtp.starttls.enable", "true");
            put("mail.smtp.ssl.protocols", "TLSv1.2");
            put("mail.debug", "true");
        }};

        // Creates a mail session. We need to supply username and
        // password for GMail authentication.
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("kodejava@gmail.com", "password");
            }
        });

        try {
            // 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);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Here is an example of debug information produce by the JavaMail API when sending an email using Gmail SMTP server.

DEBUG: JavaMail version 1.5.6
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 smtp.gmail.com ESMTP b2sm4488826pgh.33 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587
...
...

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I validate email address using Java Mail API?

This code snippet shows you how to validate an email address using the javax.mail.internet.InternetAddress class. The validate() method throws a javax.mail.internet.AddressException when the email address passed to the constructor is not a valid email address.

Here is the complete code snippet:

package org.kodejava.mail;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

public class ValidateEmail {
    public static void main(String[] args) {
        ValidateEmail demo = new ValidateEmail();

        String email = "kodejava@example.com";
        boolean isValid = demo.validateEmail(email);
        demo.printStatus(email, isValid);

        email = "kodejava.example";
        isValid = demo.validateEmail(email);
        demo.printStatus(email, isValid);
    }

    private boolean validateEmail(String email) {
        boolean isValid = false;
        try {
            // Create InternetAddress object and validated the supplied
            // address which is this case is an email address.
            InternetAddress internetAddress = new InternetAddress(email);
            internetAddress.validate();
            isValid = true;
        } catch (AddressException e) {
            e.printStackTrace();
        }
        return isValid;
    }

    private void printStatus(String email, boolean valid) {
        System.out.println(email + " is " + (valid ? "a" : "not a") +
                " valid email address");
    }
}

When running the program you will get the following message printed on the screen.

kodejava@example.com is a valid email address
kodejava.example is not a valid email address
javax.mail.internet.AddressException: Missing final '@domain' in string ``kodejava.example''
    at javax.mail.internet.InternetAddress.checkAddress(InternetAddress.java:1279)
    at javax.mail.internet.InternetAddress.validate(InternetAddress.java:1154)
    at org.kodejava.mail.ValidateEmail.validateEmail(ValidateEmail.java:25)
    at org.kodejava.mail.ValidateEmail.main(ValidateEmail.java:15)

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>javax.mail-api</artifactId>
        <version>1.5.6</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I validate email address using regular expression?

In this example we use the String‘s class matches() methods to match a string to be a valid email address based on the given regex.

This example also demonstrate the power of regular expression to validate an email address. Using regular expression makes it easier to validate data such as email address. After the code you’ll see the meaning of the regular expression used in the code below.

package org.kodejava.lang;

public class EmailAddressValidation {
    private static final String EMAIL_REGEX =
            "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";

    public static void main(String[] args) {
        EmailAddressValidation validator = new EmailAddressValidation();

        System.out.println("isValid = "
                + validator.isValidEmailAddress("user@domain.com"));
        System.out.println("isValid = "
                + validator.isValidEmailAddress("user.name@domain.com"));
        System.out.println("isValid = "
                + validator.isValidEmailAddress("user.name@domain.co.id"));
        System.out.println("isValid = "
                + validator.isValidEmailAddress("user.domain.co.id"));
    }

    /**
     * Validates email address against email regular expression.
     *
     * @param email an email address to check
     * @return true if email address is valid otherwise return false.
     */
    private boolean isValidEmailAddress(String email) {
        return email.matches(EMAIL_REGEX);
    }
}

The first ^[\\w-_\\.+]. The ^ symbols means check the first character. This the regex processor that the email address should start with a word character formed of alphanumeric value (a-z 0-9) or it can also be a hyphen, underscore, dot or a plus symbol.

The second part, *[\\w-_\\.]. The * symbol means match the preceding zero or more times. As the first part, this tell the regex processor to check for another zero or more characters, and it can also contain hyphen, underscore and a dot.

The third part, \\@([\\w]+\\.)+. This check that email address should contain the @ symbol followed by one or more word separated by the dot symbol.

The last part is, [\\w]+[\\w]$, this check that after the last period there should be another word for the domain suffix such as the co.uk or co.id. And the $ ask that the email address should end by a word character.