Over a million developers have joined DZone.

How to send an HTML email in Java (Using Google SMTP Server)

Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience, brought to you in partnership with JetBrains

In most of the business services sometimes there comes requirements to send notifications to users or administrators via email.

For example :
  • Confirming a user registration
  • Password reset via emails
Following code segments can be used to send these emails using Google SMTP server. Here I am sharing two ways to do it. 
  1. Using javax.mail.jar directly
  2. Using Apache commons email jar which wraps javax.mail 

Using javax.mail

try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "false");
            props.put("mail.smtp.ssl.enable", "true");

            Session session = Session.getInstance(props, new EmailAuth());
            Message msg = new MimeMessage(session);

            InternetAddress from = new InternetAddress("sendersEmailAddress", "Sender's name");
            msg.setFrom(from);

            InternetAddress toAddress = new InternetAddress("Receiver's email");

            msg.setRecipient(Message.RecipientType.TO, toAddress);

            msg.setSubject("Test");
            msg.setContent(msg.setContent("<html>\n" +
                    "<body>\n" +
                    "\n" +
                    "<a href=\"http://pushpalankajaya.blogspot.com\">\n" +
                    "This is a link</a>\n" +
                    "\n" +
                    "</body>\n" +
                    "</html>", "text/html");, "text/html");
            Transport.send(msg);
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();

        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }

    static class EmailAuth extends Authenticator {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication("sendersEmailAddress", "password");

        }
    }

Using Apache commons e-mail

        HtmlEmail email = new HtmlEmail();
        email.setHostName("smtp.gmail.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("sendersEmailAddress", "password"));
        email.setSSLOnConnect(true);
        email.setFrom("Senders' email");
        email.setSubject("TestMail- Alternative message");
        email.setHtmlMsg("<html>\n" +
                "<body>\n" +
                "\n" +
                "<a href=\"http://pushpalankajaya.blogspot.com\">\n" +
                "This is a link</a>\n" +
                "\n" +
                "</body>\n" +
                "</html>");
        // set the alternative message
        email.setTextMsg("This is a link: http://pushpalankajaya.blogspot.com");
        email.addTo("lanka@wso2.com");
        email.send();

Here with setTextMsg method we can set a plain text message to be shown at receiver's end if receiver is not supporting HTML content in emails.

If the gmail account used to send the email is 2-Step verification enabled and you used your usual password to send the email in code, you will get a similar error to the following.

javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required. Learn more at 534 5.7.9 http://support.google.com/accounts/bin/answer.py?answer=185833

The solution is to go to Account>Security>App passwords>Settings and generate a password for the app we are to run. 
Reference
[1] - http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/javamail/javamail.html
[2] - http://commons.apache.org/proper/commons-email/userguide.html





Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.

Topics:

Published at DZone with permission of Pushpalanka Jayawardhana, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}