java transport,java – Transport.send(消息)在以下代码中不起作用.. netbeans卡在运行部分.它不会继续下去……它永远挂在那里...

搜索热词

我曾尝试编写使用Java发送电子邮件的代码.但是这段代码不起作用.当代码执行时,它会卡在transport.send(消息)上.它永远停留在那里.此外,我不确定其余代码是否正确.

//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”协议访问SMTP over SSL,则所有属性都将命名为“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超时,我没有与任何其他连接.

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值