【问题标题】:Java Mail not working in Cloud ServerJava Mail 在云服务器中不起作用
【发布时间】:2018-07-16 19:43:51
【问题描述】:

我有一个在 GlassFish 服务器上运行的 Java EE Web 应用程序。我编写了以下代码来通过应用程序发送电子邮件。 当我在家用 PC 和笔记本电脑上测试应用程序时,它会立即发送电子邮件。当我在谷歌云服务器中运行相同的应用程序时,它会出现超时异常。可能的原因是什么?

package com.divudi.ejb;

import java.util.Properties;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Stateless
public class EmailManagerEjb {

    final static String USERNAME = "mygmailaccount@gmail.com";
    final static String PASSWORD = "mygmailpassword";
    static Session session = null;

    public void sendEmail1(String toEmail, String messageHeading, String messageBody) {
        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
        if (session == null) {
            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(USERNAME, PASSWORD);
                }
            });
        }
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(USERNAME));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(toEmail));
            message.setSubject(messageHeading);
            message.setText(messageBody);
            Transport.send(message);
            System.out.println("Send Successfully");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

    }

}

【问题讨论】:

标签: email jakarta-ee google-cloud-platform gmail jakarta-mail


【解决方案1】:

在查看了stdunbar的评论后,我为谷歌云计算引擎的端口25、465和587创建了防火墙例外。

然后一切都开始正常了。

现在电子邮件已成功发送。

【讨论】:

    【解决方案2】:

    如果您使用的是 App Engine,则可以使用 JavaMail,它使用 Mail API。或者,如果您使用的是 Compute Engine,那么我们建议您使用其他邮件服务,例如 Mailgun or Sendgrid

    【讨论】:

      猜你喜欢
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 2014-09-15
      • 1970-01-01
      • 2018-03-05
      • 2016-08-22
      相关资源
      最近更新 更多