【发布时间】: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);
}
}
}
【问题讨论】:
-
来自Sending Email from an Instance 的第一部分:
Google Compute Engine does not allow outbound connections on ports 25, 465, and 587。简而言之,Gmail 无法做到这一点。
标签: email jakarta-ee google-cloud-platform gmail jakarta-mail