Pages

Sunday, December 10, 2017

Using Gmail to send HTML emails

Repeatedly I need to add a Java code sending emails via Gmail. So just to avoid reinventing the code each time, I save here a sample that might be useful for someone else.

The maven project depends on JavaMail package:

    <dependencies>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.0</version>
        </dependency>
    </dependencies>

The java class sending emails:

public class Gmail {

    final String username = "user@gmail.com";
    final String password = "password";

    public static void main(String[] args) throws IOException, MessagingException {
        String html
                = "<html>"
                + "<body>"
                + "<div>"
                + "<h1>My Test</h1>"
                + "<a href='https://www.youtube.com/'>Click to continue</a>"
                + "</div>"
                + "</body>"
                + "</html>";
        new Gmail().send(username, "My subject", html);
    }

    Properties props;
    Authenticator authenticator;

    public Gmail() {
        props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

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

    public void send(String to, String subject, String text) throws IOException, AddressException, MessagingException {

        Session session = Session.getInstance(props, authenticator);

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        //     message.setText(text); // to send a plain text message
        message.setDataHandler(new DataHandler(new ByteArrayDataSource(text, "text/html")));

        Transport.send(message);
    }
}

With a new Gmail account, this code will work only from the second run. When the code is executed the first time, the exception will be produced because be default email applications all forbidden to access Gmail inbox via smtp.

At the same time an email with a useful information will arrive to the sender's inbox from Gmail.

Click the received link to allow the access to less secure apps. Switch the toggle switch to on.

After a confirmation email arrives to the senders inbox, the code will successfully send any emails.

The sample code execution results in a primitive email which looks like this: