forked from chenhaoxiang/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsendqqMail.java
More file actions
72 lines (61 loc) · 2.28 KB
/
sendqqMail.java
File metadata and controls
72 lines (61 loc) · 2.28 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package cn.hncu;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailSSLSocketFactory;
/**
* JavaMail发送邮件:前提是QQ邮箱里帐号设置要开启POP3/SMTP协议
*/
public class sendqqMail {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
// 开启debug调试,以便在控制台查看
prop.setProperty("mail.debug", "true");
// 设置邮件服务器主机名
prop.setProperty("mail.host", "smtp.qq.com");
// 发送服务器需要身份验证
prop.setProperty("mail.smtp.auth", "true");
// 发送邮件协议名称
prop.setProperty("mail.transport.protocol", "smtp");
// 开启SSL加密,否则会失败
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
// 创建session
Session session = Session.getInstance(prop);
// 通过session得到transport对象
Transport ts = session.getTransport();
// 连接邮件服务器:邮箱类型,帐号,授权码代替密码(更安全)
ts.connect("smtp.qq.com", "619***629", "jnjt***bdab");
// 后面的字符是授权码,用qq密码失败了
// 创建邮件
Message message = createSimpleMail(session);
// 发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
/**
* @Method: createSimpleMail
* @Description: 创建一封只包含文本的邮件
*/
public static MimeMessage createSimpleMail(Session session)
throws Exception {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 指明邮件的发件人
message.setFrom(new InternetAddress("619699629@qq.com"));
// 指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress(
"chxpostbox@126.com"));
// 邮件的标题
message.setSubject("JavaMailQQ邮件测试");
// 邮件的文本内容
message.setContent("JavaMail发送邮件成功!", "text/html;charset=UTF-8");
// 返回创建好的邮件对象
return message;
}
}