大部分人都不会注意到的JavaMail天坑
来源:互联网 发布:网络考试系统软件 编辑:程序博客网 时间:2024/06/06 04:27
问题背景
一般使用JavaMail发送邮件大致过程如下,创建同邮件服务的Session,配置Session参数等:
// Common variablesString host = "your_smtp_server";String from = "from_address";String to = "to_address";// Set propertiesProperties props = new Properties();props.put("mail.smtp.host", host);props.put("mail.debug", "true");// Get sessionSession 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 0
- 大部分人都不会注意到的JavaMail天坑
- 大部分中国人永远不会明白的道理
- 破解大部分人都纠结的简历难题!
- java extends & implements 一个一般不会注意到的重要区别
- 微信营销最重要的环节大部分人都忽略了
- 月入十万:大部分人努力的方向都错了
- 月入十万:大部分人努力的方向都错了
- 愿每一个有梦想的人都不会被辜负
- 细数iOS上那些你绝对不会注意到的神细节
- 细数iOS上那些你绝对不会注意到的神细节
- 是否大部分分布式系统使用的技术思路都差不多?
- 大部分简历没戏的原因都在这里!
- 据说大部分资深程序员都必须掌握的工具
- 一般人都不会的电脑绝技
- 什么都不会,来学习的!
- 原来我真的什么都不会!
- textfield的使用 想不会都难
- 公司永远都不会告诉你的
- 数学基础——导数
- C++中doulbe/float/int转为CString方法
- Mybatis3 快速入门
- 单片机学习札记5---定时器和中断配置
- Java之JIT编译器的总结
- 大部分人都不会注意到的JavaMail天坑
- MySQL的select语法
- ReactiveCocoa 的RACMulticastConnection使用
- 7.2 7.3 二叉树的概念和性质、存储
- 顺序队列(设计成环形队列)
- 动态代理学习笔记
- Linux ln -sf 的用法
- LeetCode 之 Container With Most Water
- poj 1050 To the Max