1 package javamail;
2
3 import java.util.Properties;
4
5 import javax.mail.Message;
6 import javax.mail.Message.RecipientType;
7 import javax.mail.MessagingException;
8 import javax.mail.Session;
9 import javax.mail.Transport;
10 import javax.mail.internet.AddressException;
11 import javax.mail.internet.InternetAddress;
12 import javax.mail.internet.MimeMessage;
13
14 public class TestMail01 {
15 public static void main(String[] args) {
16 Transport tran = null;
17 try {
18 Properties props = new Properties();
19 /**
20 * 设置邮件发送的协议,一般都是SMTP协议
21 */
22 props.setProperty("mail.transport.protocol", "smtp");
23 /**
24 * 设置发送邮件的服务器,不同的邮箱服务器不一致,可以在邮箱的帮助中查询
25 */
26 props.setProperty("mail.host", "smtp.qq.com");
27 /**
28 * 设置发送服务器验证,一些邮箱需要增加这个验证才能发送邮件
29 */
30 props.setProperty("mail.smtp.auth", "true");
31 /**
32 * 创建session
33 */
34 Session session = Session.getInstance(props);
35 //打开邮件发送的调试功能,可以看到邮件的发送过程
36 session.setDebug(true);
37 /*
38 * 创建Message对象,通过这个对象来设置邮件的发送信息
39 */
40 Message msg = new MimeMessage(session);
41 /*
42 * 设置邮件的标题
43 */
44 msg.setSubject("大家来看看,我通过java发邮件了!");
45 /*
46 * 设置邮件的内容,使用setText是设置纯文本的内容
47 */
48 msg.setText("唔哈哈哈哈哈哈!通过java发垃圾邮件了");
49 /**
50 * 设置邮件从什么地方发送的
51 */
52 msg.setFrom(new InternetAddress("415519522@qq.com"));
53 /**
54 * 设置邮件的收件人
55 */
56 msg.setRecipients(RecipientType.TO, InternetAddress.parse("xiaohui390@126.com"));
57 /**
58 * 设置邮件的抄送人
59 */
60 msg.setRecipients(RecipientType.CC, InternetAddress.parse("whui390@163.com"));
61
62 /**
63 * 创建Transport来完成邮件的发送
64 */
65 tran = session.getTransport();
66 /**
67 * 连接用户名和密码
68 */
69 tran.connect("415519522", "**********");
70 /**
71 * 发送邮件,此时如果msg中设置了收件人,但是在sendMessage的第二个参数中没有设置的话
72 * 也不会发送,所以使用tran.sendMessage来发送邮件不是一种推荐的方式
73 * 应该使用Transport.send(msg);来发送邮件
74 */
75 tran.sendMessage(msg, new InternetAddress[]{new InternetAddress("xiaohui390@126.com")});
76 } catch (AddressException e) {
77 e.printStackTrace();
78 } catch (MessagingException e) {
79 e.printStackTrace();
80 } finally {
81 try {
82 if(tran!=null) tran.close();
83 } catch (MessagingException e) {
84 e.printStackTrace();
85 }
86 }
87
88 }
89 }