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

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

问题描述

我正在使用Apache Commons Email库发送电子邮件,但是我无法通过GMail SMTP服务器发送它们。

任何人都可以提供与GMail SMTP服务器和其他人一起使用的示例代码? p>

我使用的代码不起作用:

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

SimpleEmail email = new SimpleEmail();
email.setHostName(smtp.gmail.com);
email.setAuthentication(sender@gmail.com,mypasswd);
email.setDebug(true);
email.setSmtpPort(465); (int i = 0; i< recipients.length; i ++)
{
email.addTo(recipients [i]);


}

email.setFrom(sender@gmail.com,我);
email.setSubject(Test message);
email.setMsg(这是一个简单的commons-email测试);
email.send();


解决方案

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

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

向示例代码添加以下内容以启用TLS。



对于API版本< 1.3使用:

email.setTSL(true);

该方法对于版本> = 1.3已被弃用,相反,应该使用: email.setStartTLSEnabled(true);


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

解决方案

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

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

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