Sending email in Java using Apache Commons email libs

北慕城南 提交于 2019-12-02 16:00:39
Chris Dail

Sending emails to the GMail SMTP server requires authentication and SSL. The username and password is pretty straight forward. Make sure you have the following properties set to enable authentication and SSL and it should work.

mail.smtp.auth=true
mail.smtp.starttls.enable=true

To the sample code add the following to enabled TLS.

For API-Versions < 1.3 use:
email.setTSL(true);
the method is deprecated for versions >= 1.3, and instead you should use: email.setStartTLSEnabled(true);

Please find below a code which works. Obviously, you have to add the apache jar to your project's build path.

public static void sendSimpleMail() throws Exception {
    Email email = new SimpleEmail();
    email.setSmtpPort(587);
    email.setAuthenticator(new DefaultAuthenticator("your gmail username",
            "your gmail password"));
    email.setDebug(false);
    email.setHostName("smtp.gmail.com");
    email.setFrom("me@gmail.com");
    email.setSubject("Hi");
    email.setMsg("This is a test mail ... :-)");
    email.addTo("you@gmail.com");
    email.setTLS(true);
    email.send();
    System.out.println("Mail sent!");
}

Regards, Sergiu

Hein B

using commons.email worked for me.

HtmlEmail email = new HtmlEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(465);
email.setSSL(true);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!