使用 Apache Commons 电子邮件库在 Java 中发送电子邮件 [英] Sending email in Java using Apache Commons email libs

查看:31
本文介绍了使用 Apache Commons 电子邮件库在 Java 中发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Apache Commons 电子邮件库发送电子邮件,但我无法通过 GMail SMTP 服务器发送它们.
任何人都可以提供与 GMail SMTP 服务器和其他服务器一起使用的示例代码吗?

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 = {"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();

推荐答案

向 GMail SMTP 服务器发送电子邮件需要身份验证和 SSL.用户名和密码非常简单.确保您已设置以下属性以启用身份验证和 SSL,并且它应该可以工作.

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

在示例代码中添加以下内容以启用 TLS.

To the sample code add the following to enabled TLS.

对于 API 版本

1.3 用途:
email.setTSL(true);
对于 >= 1.3 的版本不推荐使用该方法,您应该使用:email.setStartTLSEnabled(true);

这篇关于使用 Apache Commons 电子邮件库在 Java 中发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆