使用Javamail发送邮件,必需的jar包(请下载javamail的源文件,官方下载页:http://www.oracle.com/technetwork/java/javamail/index-138643.html):
mailapi.jar。定义了收发邮件所使用到的接口API;
smtp.jar。包含了发送邮件使用到的类;
pop3.jar。包含了收邮件使用到的类;
我们通常发送邮件使用的协议是smtp协议,接受邮件使用的协议是pop3协议。或者,我们直接将mail.jar加入到工程,这个jar包里边包含了java收发邮件所有的接口和类。
常用的类:
- javax.mail.Session; -------->保存连接服务器所需要的信息;
- javax.mail.Message; -------->邮件体,保存邮件的内容;
- javax.mail.Transport; -------->发送邮件的载体
- javax.mail.internet.InternetAddress; -------->邮件的地址信息
发送邮件
下边,我先列出使用Java发送邮件的最简单的一个小测试示例:
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
|
import java.util.Properties; import javax.mail.Address; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * * QQ(mail.qq.com):POP3服务器(端口995)SMTP服务器(端口465或587)。 * */ public class Demo1 { /** * @param args * @throws MessagingException */ public static void main(String[] args) throws MessagingException { String sendUserName = "wangxiangpan@126.com" ; String sendPassword = "pwd" ; Properties properties = new Properties(); properties.setProperty( "mail.smtp.auth" , "true" ); //服务器需要认证 properties.setProperty( "mail.transport.protocol" , "smtp" ); //声明发送邮件使用的端口 Session session = Session.getInstance(properties); session.setDebug( true ); //同意在当前线程的控制台打印与服务器对话信息 Message message = new MimeMessage(session); //构建发送的信息 message.setText( "你好,我是Champion.Wong!" ); //信息内容 message.setFrom( new InternetAddress( "wangxiangpan@126.com" )); //发件人 Transport transport = session.getTransport(); transport.connect( "smtp.126.com" , 25 , sendUserName, sendPassword); //连接发件人使用发件的服务器 transport.sendMessage(message, new Address[]{ new InternetAddress( "492134880@qq.com" )}); //接受邮件 transport.close(); } } |
一般的,我们使用Authenticator把用户名和密码封装起来,不透明!所以:
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
|
import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import junit.framework.TestCase; /** * javamail 发送邮件 * @author Champion Wong * Message.addRecipient(Message.Recipient recipient, Address address); 发邮件的时候指定收件人和收件人的角色 * Message.RecipientType.TO 收件人 * Message.RecipientType.CC 抄送,即发邮件的时候顺便给另一个人抄一份,不用回复!但是,上边的收件人可以看到你都抄送给了谁 * Message.RecipientType.BCC 暗送,也是发邮件的时候顺便给另一个人暗发一份,但是,不同于上边的是,收件人不能看到你都暗送给了谁 * */ public class Demo2 extends TestCase { private static final String sendUserName = "wangxiangpan@126.com" ; // 发送邮件需要连接的服务器的用户名 private static final String sendPassword = "pwd" ; // 发送邮件需要连接的服务器的密码 private static final String sendProtocol = "smtp" ; // 发送邮件使用的端口 private static final String sendHostAddress = "smtp.126.com" ; // 发送邮件使用的服务器的地址 public void test() throws AddressException, MessagingException { Properties properties = new Properties(); properties.setProperty( "mail.smtp.auth" , "true" ); // 服务器需要认证 properties.setProperty( "mail.transport.protocol" , sendProtocol); // 声明发送邮件使用的端口 properties.setProperty( "mail.host" , sendHostAddress); // 发送邮件的服务器地址 Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(sendUserName, sendPassword); } }); session.setDebug( true ); //在后台打印发送邮件的实时信息 Message message = new MimeMessage(session); message.setFrom( new InternetAddress( "wangxiangpan@126.com" )); message.setSubject( "Demo2JavaCode发送邮件测试,采用Authenticator" ); // 设置主题 message.setRecipients(Message.RecipientType.TO, InternetAddress .parse( "492134880@qq.com,wangxiangpan@126.com" )); // 发送 message.setRecipients(Message.RecipientType.CC, InternetAddress .parse( "msn_wangxiangpan@hotmail.com" )); // 抄送 message .setContent( "<span style=" font-size:20px; color:#FFCCFF " mce_style=" font-size:20px; color:#FFCCFF ">如果您看到,证明测试成功了!</span>" , "text/html;charset=gbk" ); Transport.send(message); //发送邮件 } } |
我们发送一个比较复杂的邮件,包括附件,图文:
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
|
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message.RecipientType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; /** * * @author Administrator Mr XP.Wang * MimeMultipart 一般电子邮件的容器是Multipart,定义了增加及删除电子邮件各部分内容的方法, * 但是其是抽象类,需要其子类MimeMultipart来时用MimeMessage对象 * MimeBodyPart 是BodyPart具体用于mimeMessage的一个子类,MimeBodyPart对象代表一个 * mimeMultipart对象的每一个部分 * MimeUtility.encodeText(String cn)用于解决邮件中的头部信息中中文的乱码问题 * */ public class Demo3_test { public static void main(String[] args) throws Exception { Properties properties = new Properties(); properties.setProperty( "mail.smtp.auth" , "true" ); // 服务器需要认证 properties.setProperty( "mail.transport.protocol" , "smtp" ); // 声明发送邮件使用的端口 properties.setProperty( "mail.host" , "smtp.126.com" ); // 发送邮件的服务器地址 Session session = Session.getInstance(properties, new Authenticator() { String sendUserName = "wangxiangpan@126.com" ; String sendPassword = "pwd" ; protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(sendUserName, sendPassword); } }); session.setDebug( true ); MimeMessage msg = new MimeMessage(session); // 声明一个邮件体 msg.setFrom( new InternetAddress( "/" "+MimeUtility.encodeText(" Mr XP.Wang ")+" / "<wangxiangpan@126.com>" )); msg.setSubject( "这是我的第一份复杂邮件" ); //设置邮件主题 msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(MimeUtility.encodeText( "王翔攀" )+ "<wangxiangpan@126.com>," +MimeUtility.encodeText( "三毛" )+ "<492134880@qq.com>" )); MimeMultipart msgMultipart = new MimeMultipart( "mixed" ); // 标明邮件的组合关系,混合的关系 msg.setContent(msgMultipart); // 设置邮件体 MimeBodyPart attch1 = new MimeBodyPart(); // 附件1 MimeBodyPart attch2 = new MimeBodyPart(); // 附件2 // 将附件和正文设置到这个邮件体中 msgMultipart.addBodyPart(attch1); msgMultipart.addBodyPart(attch2); msgMultipart.addBodyPart(content); // 设置第一个附件 DataSource ds1 = new FileDataSource( "F:/ACCP5.0/文件/ssh配置.txt" ); // 指定附件的数据源 DataHandler dh1 = new DataHandler(ds1); // 附件的信息 attch1.setDataHandler(dh1); // 指定附件 attch1.setFileName( "ssh.txt" ); // 设置第二个附件 DataSource ds2 = new FileDataSource( "resource/48.jpg" ); // 指定附件的数据源 DataHandler dh2 = new DataHandler(ds2); // 附件的信息 attch2.setDataHandler(dh2); // 指定附件 attch2.setFileName( "48.jpg" ); //设置邮件的正文 MimeMultipart bodyMultipart = new MimeMultipart( "related" ); //依赖关系 content.setContent(bodyMultipart); //指定正文 MimeBodyPart htmlPart = new MimeBodyPart(); MimeBodyPart gifPart = new MimeBodyPart(); bodyMultipart.addBodyPart(htmlPart); bodyMultipart.addBodyPart(gifPart); DataSource gifds = new FileDataSource( "resource/48.jpg" ); //正文的图片 DataHandler gifdh = new DataHandler(gifds); gifPart.setHeader( "Content-Location" , "http://mimg.126.net/logo/126logo.gif" ); gifPart.setDataHandler(gifdh); //设置正文的图片 htmlPart.setContent( "我只是来打酱油的,这是我的形象照!<img src=" / " mce_src=" / "" http: //mimg.126.net/logo/126logo.gif/">", "text/html;charset=gbk");//设置正文文字 msg.saveChanges(); //保存邮件 //将邮件保存成文件 OutputStream ops = new FileOutputStream( "C:/Users/Administrator/Desktop/test.eml" ); msg.writeTo(ops); ops.close(); Transport.send(msg); } } |
收取邮件
示例:Rose 收取最近一封邮件。
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
|
import java.util.Date; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Store; public class FetchMail { public static void main(String[] args) { String protocol = "pop3" ; boolean isSSL = true ; String host = "pop.163.com" ; int port = 995 ; String username = "rose@163.com" ; String password = "rose" ; Properties props = new Properties(); props.put( "mail.pop3.ssl.enable" , isSSL); props.put( "mail.pop3.host" , host); props.put( "mail.pop3.port" , port); Session session = Session.getDefaultInstance(props); Store store = null ; Folder folder = null ; try { store = session.getStore(protocol); store.connect(username, password); folder = store.getFolder( "INBOX" ); folder.open(Folder.READ_ONLY); int size = folder.getMessageCount(); Message message = folder.getMessage(size); String from = message.getFrom()[ 0 ].toString(); String subject = message.getSubject(); Date date = message.getSentDate(); System.out.println( "From: " + from); System.out.println( "Subject: " + subject); System.out.println( "Date: " + date); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } finally { try { if (folder != null ) { folder.close( false ); } if (store != null ) { store.close(); } } catch (MessagingException e) { e.printStackTrace(); } } System.out.println( "接收完毕!" ); } } |