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

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

Popular posts from this blog

Signing SOAP Messages - Generation of Enveloped XML Signatures

Tomcat JDBC Pool - Connection Leak - Catch the Culprit

How to convert WSDL to Java