简体   繁体   English

使用Apache Commons电子邮件库以Java形式发送电子邮件

[英]Sending email in Java using Apache Commons email libs

I am using Apache Commons Email library to send emails, but I am not able to send them via GMail SMTP server. 我正在使用Apache Commons电子邮件库发送电子邮件,但我无法通过GMail SMTP服务器发送它们。
Can anyone provide sample code which works with GMail SMTP server and others? 任何人都可以提供与GMail SMTP服务器和其他服务器兼容的示例代码吗?

I am using the following code which does not work: 我使用以下代码不起作用:

String[] recipients = {"receiver@gmail.com"};

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

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

email.setFrom("sender@gmail.com", "Me");
email.setSubject("Test message");
email.setMsg("This is a simple test of commons-email");
email.send();

Sending emails to the GMail SMTP server requires authentication and SSL. 将电子邮件发送到GMail SMTP服务器需要身份验证和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. 确保将以下属性设置为启用身份验证和SSL,它应该可以正常工作。

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

To the sample code add the following to enabled TLS. 对示例代码添加以下内容以启用TLS。

For API-Versions < 1.3 use: 对于API-Versions <1.3,请使用:
email.setTSL(true);
the method is deprecated for versions >= 1.3, and instead you should use: email.setStartTLSEnabled(true); 对于版本> = 1.3,不推荐使用该方法,而应使用: email.setStartTLSEnabled(true);

Please find below a code which works. 请在下面找到有效的代码。 Obviously, you have to add the apache jar to your project's build path. 显然,您必须将apache jar添加到项目的构建路径中。

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 此致,Sergiu

using commons.email worked for me. 使用commons.email为我工作。

HtmlEmail email = new HtmlEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(465);
email.setSSL(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM