【问题标题】:Sending email in Java using Apache Commons email libs使用 Apache Commons 电子邮件库在 Java 中发送电子邮件
【发布时间】:2010-10-25 07:54:17
【问题描述】:

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

我正在使用以下不起作用的代码:

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

【问题讨论】:

    标签: java email smtp gmail apache-commons-email


    【解决方案1】:

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

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

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

    对于 API 版本 email.setTSL(true);
    对于 >= 1.3 的版本,该方法已弃用,您应该使用:email.setStartTLSEnabled(true);

    【讨论】:

      【解决方案2】:

      使用 commons.email 对我有用。

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

      【讨论】:

        【解决方案3】:

        请在下面找到有效的代码。显然,您必须将 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!");
        }
        

        问候, 塞尔吉乌

        【讨论】:

          猜你喜欢
          • 2015-03-21
          • 2018-09-22
          • 1970-01-01
          • 2011-10-16
          • 1970-01-01
          • 2016-10-02
          • 2015-09-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多