【问题标题】:how can i send mail from web application如何从 Web 应用程序发送邮件
【发布时间】:2016-01-08 22:20:13
【问题描述】:

嗨,我有使用 jersey 的 web 应用程序 java,我使用 tomcat 部署了我的程序并连接到 mysql DB ...我有一个类负责向用户发送邮件。 在 localhost 上,课程工作正常并且邮件已发送,但在我部署程序并上传到服务器后,邮件不会发送给用户...

这就是类:

 public static boolean SendMail(String from, String password, String message, String to[]) {
    String host = "smtp.gmail.com";
    Properties properties = System.getProperties();
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.user", from);
    properties.put("mail.smtp.password", password);
    properties.put("mail.smtp.port", 587);
    properties.put("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(properties, null);
    MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(from));
        InternetAddress[] toAddress = new InternetAddress[to.length];
        for (int index = 0; index < to.length; index++) {
            toAddress[index] = new InternetAddress(to[index]);
        }
        for (int index = 0; index < toAddress.length; index++) {
            mimeMessage.addRecipient(Message.RecipientType.TO, toAddress[index]);
        }
        mimeMessage.setSubject("email From linkeride");
        mimeMessage.setText(message);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();
        return true;

    } catch (MessagingException me) {
        me.printStackTrace();
    }
    return false;
}

也许有人可以告诉我问题是什么?

【问题讨论】:

  • 您的主机是否运行邮件服务器?如果您想做一些测试,我知道有一种方法可以通过您的 gmail 帐户发送电子邮件。至于生产部署,您需要一个邮件服务器来连接。
  • 可能是您的服务器无法访问 SMTP 服务器或某些端口被阻止的简单情况。
  • 有错误吗?您的网络是否需要网关才能进行此类连接?
  • 没有错误..我看起来像浏览器尝试执行操作(“think..”)

标签: java email web-applications jersey port


【解决方案1】:

正如你所说,这段代码在一台机器上运行,而不是在另一台机器上运行,这似乎更像是服务器配置问题而不是编程问题。

properties.put("mail.smtp.debug", "true"); 

尝试为 SMTP 启用调试模式,这样在日志中您将全面了解您的邮件发送失败的具体步骤。

【讨论】:

  • 添加到我的代码中,这是我从浏览器中得到的:
  • HTTP 状态 500 - com.sun.mail.util.MailConnectException:无法连接到主机,端口:smtp.gmail.com,587;超时 -1;
  • java.lang.RuntimeException: com.sun.mail.util.MailConnectException: 无法连接到主机,端口:smtp.gmail.com,587;超时-1;嵌套异常是:
  • 我忘了提到在 linux 上运行的服务器.. 这可能是问题吗?
  • 似乎从您的新服务器到 gmail 服务器的连接被您服务器上的防火墙阻止了。请尝试通过禁用防火墙或为您的应用程序添加一些例外规则来运行它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-28
  • 2010-12-27
  • 1970-01-01
  • 2011-12-10
  • 2014-11-03
  • 2013-09-21
  • 1970-01-01
相关资源
最近更新 更多