Java网络编程之JavaMail发送邮件和接受邮件
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
|
package whut.mailsender; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import whut.mailreceiver.MailAuthenticator; public class SimpleSMTPSender
{ public static void main(String[]
args) { try { Properties
props= new Properties(); //传递一个邮件服务器名smtp.163.com //mail.smtp.host代表是发信人所在的邮箱服务器名 props.put( "mail.smtp.host" , "smtp.163.com" ); props.put( "mail.smtp.auth" , true ); //对于发送邮件,只需要保证发送人所在的邮件服务器正确打开就可以了 //收信人的邮箱可以是任意地址,如@163.com,@qq.com,@126.com //创建一个程序与邮件服务器的通信 Session
mailConnection=Session.getInstance(props, null ); Message
msg= new MimeMessage(mailConnection); //创建一个要输入用户名和指令的 //Session
mailConnection=Session.getInstance(props,new MailAuthenticator()); //设置发送人和接受人 Address
sender= new InternetAddress( "yyyy@163.com" ); Address
receiver= new InternetAddress( "xxx@163.com" ); /* *
群发邮件的方法 *
StringBuffer buffer=new StringBuffer(); *
buffer.append("11@163.com,") *
buffer.append("22@163.com") *
String all=buffer.toString(); *
Address[] allre=InternetAddress.parse(all); *
msg.setRecipient(Message.RecipientType.TO, allre); */ msg.setFrom(sender); msg.setRecipient(Message.RecipientType.TO,
receiver); msg.setSubject( "You
must comply" ); //msg.setContent("Hello",
"text/plain"); //下面是模拟发送带附件的邮件 //新建一个MimeMultipart对象用来存放多个BodyPart对象 Multipart
mtp= new MimeMultipart(); //------设置信件文本内容------ //新建一个存放信件内容的BodyPart对象 BodyPart
mdp= new MimeBodyPart(); //给BodyPart对象设置内容和格式/编码方式 mdp.setContent( "hello" , "text/html;charset=gb2312" ); //将含有信件内容的BodyPart加入到MimeMultipart对象中 mtp.addBodyPart(mdp); //设置信件的附件(用本地机上的文件作为附件) mdp= new MimeBodyPart(); FileDataSource
fds= new FileDataSource( "f:/webservice.doc" ); DataHandler
dh= new DataHandler(fds); mdp.setFileName( "webservice.doc" ); //可以和原文件名不一致 mdp.setDataHandler(dh); mtp.addBodyPart(mdp); //把mtp作为消息对象的内容 msg.setContent(mtp); //以上为发送带附件的方式 //先进行存储邮件 msg.saveChanges(); Transport
trans=mailConnection.getTransport( "smtp" ); String
username= "yyyy@163.com" ; String
pw= "" ; //邮件服务器名,用户名,密码 trans.connect( "smtp.163.com" ,
username, pw); trans.sendMessage(msg,
msg.getAllRecipients()); trans.close(); } catch (Exception
e) { System.err.println(e); } finally { System.exit( 0 ); } } } |
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
|
package whut.mailreceiver; import java.io.InputStreamReader; import java.io.Reader; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.Properties; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Header; import javax.mail.Message; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeUtility; //利用POP3来读取邮件 //主要用来检测消息Message的基本信息,如发送者,收信者,时间 public class POP3Client
{ public static void main(String[]
args) { Properties
props = System.getProperties(); String
host = "pop3.163.com" ; String
username = "22222222@163.com" ; String
password = "312313121" ; String
provider = "pop3" ; try { //
连接到POP3服务器 Session
ss = Session.getDefaultInstance(props, null ); //
向回话"请求"一个某种提供者的存储库,是一个POP3提供者 Store
store = ss.getStore(provider); //
连接存储库,从而可以打开存储库中的文件夹,此时是面向IMAP的 store.connect(host,
username, password); //
打开文件夹,此时是关闭的,只能对其进行删除或重命名,无法获取关闭文件夹的信息 //
从存储库的默认文件夹INBOX中读取邮件 Folder
inbox = store.getFolder( "INBOX" ); if (inbox
== null )
{ System.out.println( "NO
INBOX" ); System.exit( 1 ); } //
打开文件夹,读取信息 inbox.open(Folder.READ_ONLY); System.out.println( "TOTAL
EMAIL:" +
inbox.getMessageCount()); //
获取邮件服务器中的邮件 Message[]
messages = inbox.getMessages(); for ( int i
= 0 ;
i < messages.length; i++) { System.out.println( "------------Message--" +
(i + 1 ) + "------------" ); //
解析地址为字符串 String
from = InternetAddress.toString(messages[i].getFrom()); if (from
!= null )
{ String
cin = getChineseFrom(from); System.out.println( "From:" +
cin); } String
replyTo = InternetAddress.toString(messages[i] .getReplyTo()); if (replyTo
!= null ) { String
rest = getChineseFrom(replyTo); System.out.println( "Reply
To" +
rest); } String
to = InternetAddress.toString(messages[i] .getRecipients(Message.RecipientType.TO)); if (to
!= null )
{ String
tos = getChineseFrom(to); System.out.println( "To:" +
tos); } String
subject = messages[i].getSubject(); if (subject
!= null ) System.out.println( "Subject:" +
subject); SimpleDateFormat
sdf = new SimpleDateFormat( "yyyy-MM-dd
HH:mm:ss" ); Date
sent = messages[i].getSentDate(); if (sent
!= null ) System.out.println( "Sent
Date:" +
sdf.format(sent)); Date
ress = messages[i].getReceivedDate(); if (ress
!= null ) System.out.println( "Receive
Date:" +
sdf.format(ress)); //
显示消息的所有首部信息 //
Enumeration headers=messages[i].getAllHeaders(); //
while(headers.hasMoreElements()) //
{ //
Header h=(Header)headers.nextElement(); //
String res=h.getName(); //
String val=h.getValue(); //
System.out.println(res+":"+val); //
} //
System.out.println(); //
读取消息主题部分 //
Object content=messages[i].getContent(); //
System.out.println(content); //
根据指定的编码格式读出内容 //
Reader read=new //
InputStreamReader(messages[i].getInputStream()); //
int a=0; //
while((a=read.read())!=-1) //
{ //
System.out.print((char)a); //
} //
获取该消息的类型 //
String type=messages[i].getContentType(); //
String //
sender=InternetAddress.toString(messages[i].getFrom()); //
System.out.println("Sender:"+sender); //
System.out.println("Content-type:"+type); } //
关闭连接,但不删除服务器上的消息 //
false代表不是删除 inbox.close( false ); store.close(); } catch (Exception
e) { System.err.println(e); } } //
解决中文乱码问题 public static String
getChineseFrom(String res) { String
from = res; try { if (from.startsWith( "=?GB" )
|| from.startsWith( "=?gb" ) ||
from.startsWith( "=?UTF" ))
{ from
= MimeUtility.decodeText(from); } else { from
= new String(from.getBytes( "ISO8859_1" ), "GBK" ); } } catch (Exception
e) { e.printStackTrace(); } return from; } } |
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
|
package whut.mailreceiver; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; //口令验证 public class MailAuthenticator extends Authenticator
{ private JDialog
passwordDialog= new JDialog( new JFrame(), true ); private JLabel
mainLabel= new JLabel( "Please
enter your user name and password:" ); private JLabel
userLabel= new JLabel( "User
name:" ); private JLabel
passwordLabel= new JLabel( "Password:" ); private JTextField
usernameField= new JTextField( 20 ); private JPasswordField
passwordField= new JPasswordField( 20 ); private JButton
okButton= new JButton( "OK" ); public MailAuthenticator() { this ( "" ); } public MailAuthenticator(String
username) { Container
pane=passwordDialog.getContentPane(); pane.setLayout( new GridLayout( 4 , 1 )); pane.add(mainLabel); JPanel
p2= new JPanel(); p2.add(userLabel); p2.add(usernameField); pane.add(p2); JPanel
p3= new JPanel(); p3.add(passwordLabel); p3.add(passwordField); pane.add(p3); JPanel
p4= new JPanel(); p4.add(okButton); pane.add(p4); passwordDialog.setSize( 400 , 200 ); ActionListener
al= new HideDialog(); okButton.addActionListener(al); usernameField.addActionListener(al); passwordField.addActionListener(al); } class HideDialog implements ActionListener { public void actionPerformed(ActionEvent
e) { passwordDialog.hide(); } } @Override protected PasswordAuthentication
getPasswordAuthentication() { //
TODO Auto-generated method stub passwordDialog.show(); //getPassword是返回的字符数组 String
username=usernameField.getText(); String
password= new String(passwordField.getPassword()); passwordField.setText( "" ); return new PasswordAuthentication(username,password); } } |
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
|
package whut.mailsender; import javax.mail.Part; import javax.mail.internet.MimeUtility; import sun.misc.BASE64Decoder; public class StringUtil
{ //发信人,收信人,回执人邮件中有中文处理乱码,res为获取的地址 //http默认的编码方式为ISO8859_1 //对含有中文的发送地址,使用MimeUtility.decodeTex方法 //对其他则把地址从ISO8859_1编码转换成gbk编码 public static String
getChineseFrom(String res) { String
from = res; try { if (from.startsWith( "=?GB" )
|| from.startsWith( "=?gb" ) ||
from.startsWith( "=?UTF" ))
{ from
= MimeUtility.decodeText(from); } else { from
= new String(from.getBytes( "ISO8859_1" ), "GBK" ); } } catch (Exception
e) { e.printStackTrace(); } return from; } //转换为GBK编码 public static String
toChinese(String strvalue) { try { if (strvalue
== null ) return null ; else { strvalue
= new String(strvalue.getBytes( "ISO8859_1" ), "GBK" ); return strvalue; } } catch (Exception
e) { return null ; } } //接收邮件时,获取某个邮件的中文附件名,出现乱码 //对于用base64编码过的中文,则采用base64解码, //否则对附件名进行ISO8859_1到gbk的编码转换 public static String
getFileChinese(Part part) throws Exception
{ String
temp = part.getFileName(); //
part为Part实例 if ((temp.startsWith( "=?GBK?" )
&& temp.endsWith( "?=" )) ||
(temp.startsWith( "=?gbk?b?" )
&& temp.endsWith( "?=" )))
{ temp
= StringUtil.getFromBASE64(temp.substring( 8 ,
temp.indexOf( "?=" )
- 1 )); } else { temp
= StringUtil.toChinese(temp); } return temp; } public static String
getFromBASE64(String s) { if (s
== null ) return null ; BASE64Decoder
decoder = new BASE64Decoder(); try { byte []
b = decoder.decodeBuffer(s); return new String(b); } catch (Exception
e) { return null ; } } } |
如果你喜欢本文, 请长按二维码,关注公众号 分布式编程.
作者:分布式编程
出处:https://zthinker.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。