开启 SSL 加密
网上搜了一下,其他比如163、新浪邮箱不需要 SSL 加密,可以放弃 QQ 邮箱。
网上还有种说法,把 smtp.qq.com 换成 smtp.exmail.qq.com也不需要 SSL加密,但是笔者没有run成功。所以还是老老实实加上 SSL 加密吧。
下面的代码开启了 SSL 加密
1
2
3
4
|
MailSSLSocketFactory sf = newMailSSLSocketFactory();
sf.setTrustAllHosts(true); props.put("mail.smtp.ssl.enable","true"); props.put("mail.smtp.ssl.socketFactory", sf); |
成功了,控制台输出 Log 和效果图如下
1
2
3
4
5
6
7
8
9
10
|
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.qq.com", port 465, isSSL true 220smtp.qq.com Esmtp QQ Mail Server DEBUG SMTP: connected to host "smtp.qq.com", port: 465 ... data2016-01-1917:00:44Tue . 250Ok: queued as QUIT 221Bye |
完整代码示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
publicclass MailTool {
publicstatic void main(String[] args) throwsMessagingException, GeneralSecurityException { Properties props = newProperties(); // 开启debug调试 props.setProperty("mail.debug","true"); // 发送服务器需要身份验证 props.setProperty("mail.smtp.auth","true"); // 设置邮件服务器主机名 props.setProperty("mail.host","smtp.qq.com"); // 发送邮件协议名称 props.setProperty("mail.transport.protocol","smtp"); MailSSLSocketFactory sf = newMailSSLSocketFactory(); sf.setTrustAllHosts(true); props.put("mail.smtp.ssl.enable","true"); props.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getInstance(props); Message msg = newMimeMessage(session); msg.setSubject("seenews 错误"); StringBuilder builder = newStringBuilder(); builder.append("url = " + "http://blog.csdn.net/never_cxb/article/details/50524571"); builder.append("\n页面爬虫错误"); builder.append("\n时间 " + TimeTool.getCurrentTime()); msg.setText(builder.toString()); msg.setFrom(newInternetAddress("**发送人的邮箱地址**")); Transport transport = session.getTransport(); transport.connect("smtp.qq.com","**发送人的邮箱地址**","**你的邮箱密码或者授权码**"); transport.sendMessage(msg,newAddress[] { newInternetAddress("**接收人的邮箱地址**") }); transport.close(); } |