gpt4 book ai didi

java - Transport.send(message) 在下面的代码中不起作用..netbeans 卡在了运行部分。它不会继续下去..它永远卡在那里

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:40:41 26 4
gpt4 key购买 nike

我尝试编写代码使用 Java 发送电子邮件。但是这段代码不起作用。执行代码时,它会卡在 transport.send(message) 处。它永远卡在那里。另外我不确定其余代码是否正确。

  //first from, to, subject, & text values are set
public class SendMail {
private String from;
private String to;
private String subject;
private String text;


public SendMail(String from, String to, String subject, String text){
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
}

//send method is called in the end
public void send(){

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");

Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);

InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage); // this is where code hangs
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

最佳答案

我遇到了完全相同的问题,其他人报告间歇性故障。原因是使用 SMTP 的 Transport.send 有两个无限超时,这会导致您的进程挂起!

来自 SUN 文档:

mail.smtp.connectiontimeout int 以毫秒为单位的套接字连接超时值。 默认是无限超时。

mail.smtp.timeout int 以毫秒为单位的套接字 I/O 超时值。 默认是无限超时。

为了不永远“挂起”,你可以明确地设置这些:

来自 SUN:属性总是设置为字符串; Type 列描述了如何解释字符串。例如,使用

    props.put("mail.smtp.port", "888");

请注意,如果您使用“smtps”协议(protocol)通过 SSL 访问 SMTP,则所有属性都将命名为“mail.smtps.*”。

因此,如果您设置了两个超时,您应该得到一个“MessagingException”,您可以使用 try/catch 来处理它,而不是让进程挂起。

假设您使用的是 smtp,添加以下内容,其中 t1 和 t2 是您的超时时间(以毫秒为单位):

    props.put("mail.smtp.connectiontimeout", "t1");
props.put("mail.smtp.timeout", "t2");

当然,这不会解决超时的根本原因,但可以让您优雅地处理问题。

感谢 Siegfried Goeschl 在 Apache Commons 上的帖子

PS:我遇到的问题的根本原因似乎与我在旅行时使用的网络连接有关。显然,该连接导致了 SMTP 超时,而我在任何其他连接中都没有遇到过这种情况。

关于java - Transport.send(message) 在下面的代码中不起作用..netbeans 卡在了运行部分。它不会继续下去..它永远卡在那里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8907229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com