- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我尝试编写代码使用 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/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!