Java 云服务器中的邮件不工作

Java Mail not working in Cloud Server

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

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

    }

}

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

然后一切开始正常工作。

至此邮件发送成功

如果您使用的是 App Engine,则可以使用 JavaMail which uses the Mail API. Alternatively, if you are using Compute Engine, then we recommend that you use another mail service like Mailgun or Sendgrid