Sending email in Java using Apache Commons email libs
Asked Answered
M

3

12

I am using Apache Commons Email library to send emails, but I am not able to send them via GMail SMTP server.
Can anyone provide sample code which works with GMail SMTP server and others?

I am using the following code which does not work:

String[] recipients = {"[email protected]"};

SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.gmail.com");
email.setAuthentication("[email protected]", "mypasswd");
email.setDebug(true);
email.setSmtpPort(465);

for (int i = 0; i < recipients.length; i++)
{
    email.addTo(recipients[i]);
}

email.setFrom("[email protected]", "Me");
email.setSubject("Test message");
email.setMsg("This is a simple test of commons-email");
email.send();
Mindi answered 11/5, 2009 at 16:2 Comment(0)
A
10

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);

Appearance answered 11/5, 2009 at 16:7 Comment(0)
N
10

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("[email protected]");
    email.setSubject("Hi");
    email.setMsg("This is a test mail ... :-)");
    email.addTo("[email protected]");
    email.setTLS(true);
    email.send();
    System.out.println("Mail sent!");
}

Regards, Sergiu

Nairobi answered 10/10, 2010 at 12:3 Comment(0)
C
2

using commons.email worked for me.

HtmlEmail email = new HtmlEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(465);
email.setSSL(true);
Caius answered 22/7, 2010 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.