定时器定时批量发邮件的代码,不够总是两三天定时器就停了,是因为Transport类

 

源代码

// Common variables
String host = "your_smtp_server";
String from = "from_address";
String to = "to_address";

// Set properties
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.debug", "true");
 
// Get session
Session session = Session.getInstance(props);
 
try {
    // Instantiate a message
    Message msg = new MimeMessage(session);
 
    // Set the FROM message
    msg.setFrom(new InternetAddress(from));
 
    // The recipients can be more than one so we use an array but you can
    // use 'new InternetAddress(to)' for only one address.
    InternetAddress[] address = {new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, address);
 
    // Set the message subject and date we sent it.
    msg.setSubject("Email from JavaMail test");
    msg.setSentDate(new Date());
 
    // Set message content
    msg.setText("This is the text for this simple demo using JavaMail.");
 
    // Send the message
    Transport.send(msg);
}
catch (MessagingException mex) {
    mex.printStackTrace();
}

 

解析
*注意加粗部分,翻译过来就是“默认时间无穷大”,总之一句话:你要不配置这几个参数,邮箱发送的等待时间可能是无穷大,出现异常后(比如邮箱服务器繁忙)客户端有可能永远在等待往服务器读写消息。这里涉及到跟服务器间的socket交互。*如下图,JavaMail在socket读写过程中有可能无限等待下去

这里写图片描述

 

 

解决方法

把JavaMail重构成异步,避免阻塞核心业务逻辑。
为JavaMail设置超时时间


		Properties props = new Properties();
		props.put("mail.smtp.timeout", 10000);
		props.put("mail.smtp.connectiontimeout", 10000);
		props.put("mail.smtp.writetimeout", 10000);
        props.put("mail.smtp.host", host);
        props.put("mail.debug", "true");
       // Get session
        Session session = Session.getInstance(props);

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值