首页 > 代码库 > Android使用javamail收发邮件
Android使用javamail收发邮件
Android里访问网络、收发短信都还是经常用到的功能,但是这次需求是可以收发邮件,网上搜了下,这里转一个,博主写的几个工具类确实非常好用,转帖过来,下面是需要用到的资源和工具类文件
http://pan.baidu.com/s/1hqejT7A
在发送多用户邮件中我添加了发送带附件的邮件的代码
1 发送邮件
今天学习了一下JavaMail,javamail发送邮件确实是一个比较麻烦的问题不用第三方邮件程序。为了以后使用方便,自己写了段代码.
Javamail-Android配置步骤:
下载Android版本JavaMail包,additional.jar、mail.jar和activation.jar,下载地址JavaMail-Android
在项目与src同一目录级别下,新建文件夹lib,将下载的3个jar包放入该文件夹
右键->Properties->Java Build Path->Libraries,选择Add External JARs,找到项目下lib目录的3个jar包
我的代码有三个类:
第一个类:MailSenderInfo.java
01
package com.util.mail;
02
/**
03
- 发送邮件需要使用的基本信息
04
/
05
importjava.util.Properties;
06
public classMailSenderInfo {
07
// 发送邮件的服务器的IP和端口
08
privateString mailServerHost;
09
privateString mailServerPort = “25”;
10
// 邮件发送者的地址
11
privateString fromAddress;
12
// 邮件接收者的地址
13
privateString toAddress;
14
// 登陆邮件发送服务器的用户名和密码
15
privateString userName;
16
privateString password;
17
// 是否需要身份验证
18
private booleanvalidate = false;
19
// 邮件主题
20
privateString subject;
21
// 邮件的文本内容
22
privateString content;
23
// 邮件附件的文件名
24
privateString[] attachFileNames;
25
/*
26- 获得邮件会话属性
27
*/
28
publicProperties getProperties(){
29
Properties p = newProperties();
30
p.put(“mail.smtp.host”, this.mailServerHost);
31
p.put(“mail.smtp.port”, this.mailServerPort);
32
p.put(“mail.smtp.auth”, validate ? “true”: “false”);
33
returnp;
34
}
35
publicString getMailServerHost() {
36
returnmailServerHost;
37
}
38
public voidsetMailServerHost(String mailServerHost) {
39
this.mailServerHost = mailServerHost;
40
}
41
publicString getMailServerPort() {
42
returnmailServerPort;
43
}
44
public voidsetMailServerPort(String mailServerPort) {
45
this.mailServerPort = mailServerPort;
46
}
47
public booleanisValidate() {
48
returnvalidate;
49
}
50
public void setValidate(booleanvalidate) {
51
this.validate = validate;
52
}
53
publicString[] getAttachFileNames() {
54
returnattachFileNames;
55
}
56
public voidsetAttachFileNames(String[] fileNames) {
57
this.attachFileNames = fileNames;
58
}
59
publicString getFromAddress() {
60
returnfromAddress;
61
}
62
public voidsetFromAddress(String fromAddress) {
63
this.fromAddress = fromAddress;
64
}
65
publicString getPassword() {
66
returnpassword;
67
}
68
public voidsetPassword(String password) {
69
this.password = password;
70
}
71
publicString getToAddress() {
72
returntoAddress;
73
}
74
public voidsetToAddress(String toAddress) {
75
this.toAddress = toAddress;
76
}
77
publicString getUserName() {
78
returnuserName;
79
}
80
public voidsetUserName(String userName) {
81
this.userName = userName;
82
}
83
publicString getSubject() {
84
returnsubject;
85
}
86
public voidsetSubject(String subject) {
87
this.subject = subject;
88
}
89
publicString getContent() {
90
returncontent;
91
}
92
public voidsetContent(String textContent) {
93
this.content = textContent;
94
}
95
}
第二个类:MultiMailsender.java
001
package com.util.mail;
002
- 获得邮件会话属性
003
import java.util.Date;
004
import java.util.Properties;
005
006
import javax.mail.Address;
007
import javax.mail.BodyPart;
008
import javax.mail.Message;
009
import javax.mail.MessagingException;
010
import javax.mail.Multipart;
011
import javax.mail.Session;
012
import javax.mail.Transport;
013
import javax.mail.internet.InternetAddress;
014
import javax.mail.internet.MimeBodyPart;
015
import javax.mail.internet.MimeMessage;
016
import javax.mail.internet.MimeMultipart;
017
018
/**
019
- 发送邮件给多个接收者、抄送邮件
020
*/
021
public class MultiMailsender {
022
023
024
/**
025
* 以文本格式发送邮件
026
* @param mailInfo 待发送的邮件的信息
027
*/
028
public booleansendTextMail(MultiMailSenderInfo mailInfo) {
029
// 判断是否需要身份认证
030
MyAuthenticator authenticator = null;
031
Properties pro = mailInfo.getProperties();
032
if(mailInfo.isValidate()) {
033
// 如果需要身份认证,则创建一个密码验证器
034
authenticator = newMyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
035
}
036
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
037
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
038
try{
039
// 根据session创建一个邮件消息
040
Message mailMessage = newMimeMessage(sendMailSession);
041
// 创建邮件发送者地址
042
Address from = newInternetAddress(mailInfo.getFromAddress());
043
// 设置邮件消息的发送者
044
mailMessage.setFrom(from);
045
// 创建邮件的接收者地址,并设置到邮件消息中
046
Address[] tos = null;
047
String[] receivers = mailInfo.getReceivers();
048
if (receivers != null){
049
// 为每个邮件接收者创建一个地址
050
tos = new InternetAddress[receivers.length + 1];
051
tos[0] = new InternetAddress(mailInfo.getToAddress());
052
for (int i=0; i<receivers.length; i++){
053
tos[i+1] = new InternetAddress(receivers[i]);
054
}
055
} else {
056
tos = new InternetAddress[1];
057
tos[0] = new InternetAddress(mailInfo.getToAddress());
058
}
059
060
// Message.RecipientType.TO属性表示接收者的类型为TO
061
mailMessage.setRecipients(Message.RecipientType.TO,tos);
062
// 设置邮件消息的主题
063
mailMessage.setSubject(mailInfo.getSubject());
064
// 设置邮件消息发送的时间
065
mailMessage.setSentDate(newDate());
066
// 设置邮件消息的主要内容
067
String mailContent = mailInfo.getContent();
068
mailMessage.setText(mailContent);
069
// 发送邮件
070
Transport.send(mailMessage);
071
returntrue;
072
} catch(MessagingException ex) {
073
ex.printStackTrace();
074
}
075
returnfalse;
076
}
077
/**
078
* 发送邮件给多个接收者,以Html内容
079
* @param mailInfo 带发送邮件的信息
080
* <a href="http://my.oschina.net/u/556800" class="referer" target="_blank">@return</a>
081
*/
082
public static boolean sendMailtoMultiReceiver(MultiMailSenderInfo mailInfo){
083
MyAuthenticator authenticator = null;
084
if (mailInfo.isValidate()) {
085
authenticator = new MyAuthenticator(mailInfo.getUserName(),
086
mailInfo.getPassword());
087
}
088
Session sendMailSession = Session.getInstance(mailInfo
089
.getProperties(), authenticator);
090
try {
091
Message mailMessage = new MimeMessage(sendMailSession);
092
// 创建邮件发送者地址
093
Address from = new InternetAddress(mailInfo.getFromAddress());
094
mailMessage.setFrom(from);
095
// 创建邮件的接收者地址,并设置到邮件消息中
096
Address[] tos = null;
097
String[] receivers = mailInfo.getReceivers();
098
if (receivers != null){
099
// 为每个邮件接收者创建一个地址
100
tos = new InternetAddress[receivers.length + 1];
101
tos[0] = new InternetAddress(mailInfo.getToAddress());
102
for (int i=0; i<receivers.length; i++){
103
tos[i+1] = new InternetAddress(receivers[i]);
104
}
105
} else {
106
tos = new InternetAddress[1];
107
tos[0] = new InternetAddress(mailInfo.getToAddress());
108
}
109
// 将所有接收者地址都添加到邮件接收者属性中
110
mailMessage.setRecipients(Message.RecipientType.TO, tos);
111
112
mailMessage.setSubject(mailInfo.getSubject());
113
mailMessage.setSentDate(new Date());
114
// 设置邮件内容
115
Multipart mainPart = new MimeMultipart();
116
BodyPart html = new MimeBodyPart();
117
html.setContent(mailInfo.getContent(), "text/html; charset=GBK");
118
mainPart.addBodyPart(html);
119
mailMessage.setContent(mainPart);
120
// 发送邮件
121
Transport.send(mailMessage);
122
return true;
123
} catch (MessagingException ex) {
124
ex.printStackTrace();
125
}
126
return false;
127
}
128
129
/**
130
* 发送带抄送的邮件
131
* @param mailInfo 待发送邮件的消息
132
* <a href="http://my.oschina.net/u/556800" class="referer" target="_blank">@return</a>
133
*/
134
public static boolean sendMailtoMultiCC(MultiMailSenderInfo mailInfo){
135
MyAuthenticator authenticator = null;
136
if (mailInfo.isValidate()) {
137
authenticator = new MyAuthenticator(mailInfo.getUserName(),
138
mailInfo.getPassword());
139
}
140
Session sendMailSession = Session.getInstance(mailInfo
141
.getProperties(), authenticator);
142
try {
143
Message mailMessage = new MimeMessage(sendMailSession);
144
// 创建邮件发送者地址
145
Address from = new InternetAddress(mailInfo.getFromAddress());
146
mailMessage.setFrom(from);
147
// 创建邮件的接收者地址,并设置到邮件消息中
148
Address to = new InternetAddress(mailInfo.getToAddress());
149
mailMessage.setRecipient(Message.RecipientType.TO, to);
150
151
// 获取抄送者信息
152
String[] ccs = mailInfo.getCcs();
153
if (ccs != null){
154
// 为每个邮件接收者创建一个地址
155
Address[] ccAdresses = new InternetAddress[ccs.length];
156
for (int i=0; i<ccs.length; i++){
157
ccAdresses[i] = new InternetAddress(ccs[i]);
158
}
159
// 将抄送者信息设置到邮件信息中,注意类型为Message.RecipientType.CC
160
mailMessage.setRecipients(Message.RecipientType.CC, ccAdresses);
161
}
162
163
mailMessage.setSubject(mailInfo.getSubject());
164
mailMessage.setSentDate(new Date());
165
// 设置邮件内容
166
Multipart mainPart = new MimeMultipart();
167
BodyPart html = new MimeBodyPart();
168
html.setContent(mailInfo.getContent(), "text/html; charset=GBK");
169
mainPart.addBodyPart(html);
170
mailMessage.setContent(mainPart);
171
// 发送邮件
172
Transport.send(mailMessage);
173
return true;
174
} catch (MessagingException ex) {
175
ex.printStackTrace();
176
}
177
return false;
178
}
179
180
/**
181
* 发送多接收者类型邮件的基本信息
182
*/
183
public static class MultiMailSenderInfo extends MailSenderInfo{
184
// 邮件的接收者,可以有多个
185
private String[] receivers;
186
// 邮件的抄送者,可以有多个
187
private String[] ccs;
188
189
public String[] getCcs() {
190
return ccs;
191
}
192
public void setCcs(String[] ccs) {
193
this.ccs = ccs;
194
}
195
public String[] getReceivers() {
196
return receivers;
197
}
198
public void setReceivers(String[] receivers) {
199
this.receivers = receivers;
200
}
201
}
202
}
第三个类:MyAuthenticator.java
01
package com.util.mail;
02
03
import javax.mail.*;
04
05
public class MyAuthenticator extends Authenticator{
06
String userName=null;
07
String password=null;
08
09
public MyAuthenticator(){
10
}
11
publicMyAuthenticator(String username, String password) {
12
this.userName = username;
13
this.password = password;
14
}
15
protected PasswordAuthentication getPasswordAuthentication(){
16
return new PasswordAuthentication(userName, password);
17
}
18
}
下面给出使用上面三个类的代码:
01
public static void main(String[] args){
02
//这个类主要是设置邮件
03
MultiMailSenderInfo mailInfo = newMultiMailSenderInfo();
04
mailInfo.setMailServerHost("smtp.163.com");
05
mailInfo.setMailServerPort("25");
06
mailInfo.setValidate(true);
07
mailInfo.setUserName("xxx@163.com");
08
mailInfo.setPassword("**********");//您的邮箱密码
09
mailInfo.setFromAddress("xxx@163.com");
10
mailInfo.setToAddress("xxx@163.com");
11
mailInfo.setSubject("设置邮箱标题");
12
mailInfo.setContent("设置邮箱内容");
13
String[] receivers = newString[]{"***@163.com", "***@tom.com"};
14
String[] ccs = receivers; mailInfo.setReceivers(receivers);
15
mailInfo.setCcs(ccs);
16
//这个类主要来发送邮件
17
MultiMailsender sms = newMultiMailsender();
18
sms.sendTextMail(mailInfo);//发送文体格式
19
MultiMailsender.sendHtmlMail(mailInfo);//发送html格式
20
MultiMailsender.sendMailtoMultiCC(mailInfo);//发送抄送
最后,给出朋友们几个注意的地方:
1、使用此代码你可以完成你的javamail的邮件发送功能、发多个邮箱。三个类缺一不可。
2、这三个类我打包是用的com.util.mail包,如果不喜欢,你可以自己改,但三个类文件必须在同一个包中
3、不要使用你刚刚注册过的邮箱在程序中发邮件,如果你的163邮箱是刚注册不久,那你就不要使用“smtp.163.com”。因为你发不出去。刚注册的邮箱是不会给你这种权限的,也就是你不能通过验证。要使用你经常用的邮箱,而且时间比较长的。
4、另一个问题就是mailInfo.setMailServerHost(“smtp.163.com”);与mailInfo.setFromAddress(“xxx@163.com”);这两句话。即如果你使用163smtp服务器,那么发送邮件地址就必须用163的邮箱,如果不的话,是不会发送成功的。
5、关于javamail验证错误的问题,网上的解释有很多,但我看见的只有一个。就是我的第三个类。你只要复制全了代码,我想是不会有问题的。
6、 然后在Android项目中添加网络访问权限
2 接收邮件
package org.davidfang.mail;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
public class ReciveMail {
private MimeMessage msg = null; private String saveAttchPath = ""; private StringBuffer bodytext = new StringBuffer(); private String dateformate = "yy-MM-dd HH:mm"; public ReciveMail(MimeMessage msg){ this.msg = msg; } public void setMsg(MimeMessage msg) { this.msg = msg; } /** * 获取发送邮件者信息 * @return * @throws MessagingException */ public String getFrom() throws MessagingException{ InternetAddress[] address = (InternetAddress[]) msg.getFrom(); String from = address[0].getAddress(); if(from == null){ from = ""; } String personal = address[0].getPersonal(); if(personal == null){ personal = ""; } String fromaddr = personal +"<"+from+">"; return fromaddr; } /** * 获取邮件收件人,抄送,密送的地址和信息。根据所传递的参数不同 "to"-->收件人,"cc"-->抄送人地址,"bcc"-->密送地址 * @param type * @return * @throws MessagingException * @throws UnsupportedEncodingException */ public String getMailAddress(String type) throws MessagingException, UnsupportedEncodingException{ String mailaddr = ""; String addrType = type.toUpperCase(); InternetAddress[] address = null; if(addrType.equals("TO")||addrType.equals("CC")||addrType.equals("BCC")){ if(addrType.equals("TO")){ address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.TO); } if(addrType.equals("CC")){ address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.CC); } if(addrType.equals("BCC")){ address = (InternetAddress[]) msg.getRecipients(Message.RecipientType.BCC); } if(address != null){ for(int i=0;i<address.length;i++){ String mail = address[i].getAddress(); if(mail == null){ mail = ""; }else{ mail = MimeUtility.decodeText(mail); } String personal = address[i].getPersonal(); if(personal == null){ personal = ""; }else{ personal = MimeUtility.decodeText(personal); } String compositeto = personal +"<"+mail+">"; mailaddr += ","+compositeto; } mailaddr = mailaddr.substring(1); } }else{ throw new RuntimeException("Error email Type!"); } return mailaddr; } /** * 获取邮件主题 * @return * @throws UnsupportedEncodingException * @throws MessagingException */ public String getSubject() throws UnsupportedEncodingException, MessagingException{ String subject = ""; subject = MimeUtility.decodeText(msg.getSubject()); if(subject == null){ subject = ""; } return subject; } /** * 获取邮件发送日期 * @return * @throws MessagingException */ public String getSendDate() throws MessagingException{ Date sendDate = msg.getSentDate(); SimpleDateFormat smd = new SimpleDateFormat(dateformate); return smd.format(sendDate); } /** * 获取邮件正文内容 * @return */ public String getBodyText(){ return bodytext.toString(); } /** * 解析邮件,将得到的邮件内容保存到一个stringBuffer对象中,解析邮件 主要根据MimeType的不同执行不同的操作,一步一步的解析 * @param part * @throws MessagingException * @throws IOException */ public void getMailContent(Part part) throws MessagingException, IOException{ String contentType = part.getContentType(); int nameindex = contentType.indexOf("name"); boolean conname = false; if(nameindex != -1){ conname = true; } System.out.println("CONTENTTYPE:"+contentType); if(part.isMimeType("text/plain")&&!conname){ bodytext.append((String)part.getContent()); }else if(part.isMimeType("text/html")&&!conname){ bodytext.append((String)part.getContent()); }else if(part.isMimeType("multipart/*")){ Multipart multipart = (Multipart) part.getContent(); int count = multipart.getCount(); for(int i=0;i<count;i++){ getMailContent(multipart.getBodyPart(i)); } }else if(part.isMimeType("message/rfc822")){ getMailContent((Part) part.getContent()); } } /** * 判断邮件是否需要回执,如需回执返回true,否则返回false * @return * @throws MessagingException */ public boolean getReplySign() throws MessagingException{ boolean replySign = false; String needreply[] = msg.getHeader("Disposition-Notification-TO"); if(needreply != null){ replySign = true; } return replySign; } /** * 获取此邮件的message-id * @return * @throws MessagingException */ public String getMessageId() throws MessagingException{ return msg.getMessageID(); } /** * 判断此邮件是否已读,如果未读则返回false,已读返回true * @return * @throws MessagingException */ public boolean isNew() throws MessagingException{ boolean isnew = false; Flags flags = ((Message)msg).getFlags(); Flags.Flag[] flag = flags.getSystemFlags(); System.out.println("flags‘s length:"+flag.length); for(int i=0;i<flag.length;i++){ if(flag[i]==Flags.Flag.SEEN){ isnew = true; System.out.println("seen message ......."); break; } } return isnew; } /** * 判断是是否包含附件 * @param part * @return * @throws MessagingException * @throws IOException */ public boolean isContainAttch(Part part) throws MessagingException, IOException{ boolean flag = false; String contentType = part.getContentType(); if(part.isMimeType("multipart/*")){ Multipart multipart = (Multipart) part.getContent(); int count = multipart.getCount(); for(int i=0;i<count;i++){ BodyPart bodypart = multipart.getBodyPart(i); String dispostion = bodypart.getDisposition(); if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(Part.INLINE))){ flag = true; }else if(bodypart.isMimeType("multipart/*")){ flag = isContainAttch(bodypart); }else{ String conType = bodypart.getContentType(); if(conType.toLowerCase().indexOf("appliaction")!=-1){ flag = true; } if(conType.toLowerCase().indexOf("name")!=-1){ flag = true; } } } }else if(part.isMimeType("message/rfc822")){ flag = isContainAttch((Part) part.getContent()); } return flag; } /** * 保存附件 * @param part * @throws MessagingException * @throws IOException */ public void saveAttchMent(Part part) throws MessagingException, IOException{ String filename = ""; if(part.isMimeType("multipart/*")){ Multipart mp = (Multipart) part.getContent(); for(int i=0;i<mp.getCount();i++){ BodyPart mpart = mp.getBodyPart(i); String dispostion = mpart.getDisposition(); if((dispostion != null)&&(dispostion.equals(Part.ATTACHMENT)||dispostion.equals(Part.INLINE))){ filename = mpart.getFileName(); if(filename.toLowerCase().indexOf("gb2312")!=-1){ filename = MimeUtility.decodeText(filename); } saveFile(filename,mpart.getInputStream()); }else if(mpart.isMimeType("multipart/*")){ saveAttchMent(mpart); }else{ filename = mpart.getFileName(); if(filename != null&&(filename.toLowerCase().indexOf("gb2312")!=-1)){ filename = MimeUtility.decodeText(filename); } saveFile(filename,mpart.getInputStream()); } } }else if(part.isMimeType("message/rfc822")){ saveAttchMent((Part) part.getContent()); } } /** * 获得保存附件的地址 * @return */ public String getSaveAttchPath() { return saveAttchPath; } /** * 设置保存附件地址 * @param saveAttchPath */ public void setSaveAttchPath(String saveAttchPath) { this.saveAttchPath = saveAttchPath; } /** * 设置日期格式 * @param dateformate */ public void setDateformate(String dateformate) { this.dateformate = dateformate; } /** * 保存文件内容 * @param filename * @param inputStream * @throws IOException */ private void saveFile(String filename, InputStream inputStream) throws IOException { String osname = System.getProperty("os.name"); String storedir = getSaveAttchPath(); String sepatror = ""; if(osname == null){ osname = ""; } if(osname.toLowerCase().indexOf("win")!=-1){ sepatror = "//"; if(storedir==null||"".equals(storedir)){ storedir = "d://temp"; } }else{ sepatror = "/"; storedir = "/temp"; } File storefile = new File(storedir+sepatror+filename); System.out.println("storefile‘s path:"+storefile.toString()); BufferedOutputStream bos = null; BufferedInputStream bis = null; try { bos = new BufferedOutputStream(new FileOutputStream(storefile)); bis = new BufferedInputStream(inputStream); int c; while((c= bis.read())!=-1){ bos.write(c); bos.flush(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ bos.close(); bis.close(); } } public void recive(Part part,int i) throws MessagingException, IOException{ System.out.println("------------------START-----------------------"); System.out.println("Message"+i+" subject:" + getSubject()); System.out.println("Message"+i+" from:" + getFrom()); System.out.println("Message"+i+" isNew:" + isNew()); boolean flag = isContainAttch(part); System.out.println("Message"+i+" isContainAttch:" +flag); System.out.println("Message"+i+" replySign:" + getReplySign()); getMailContent(part); System.out.println("Message"+i+" content:" + getBodyText()); setSaveAttchPath("c://temp//"+i); if(flag){ saveAttchMent(part); } System.out.println("------------------END-----------------------"); } public static void main(String[] args) throws MessagingException, IOException { Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.sina.com"); props.setProperty("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props,null); URLName urlname = new URLName("pop3","pop.qq.com",110,null,"715881036","kingsoft"); Store store = session.getStore(urlname); store.connect(); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); Message msgs[] = folder.getMessages(); int count = msgs.length; System.out.println("Message Count:"+count); ReciveMail rm = null; for(int i=0;i<count;i++){ rm = new ReciveMail((MimeMessage) msgs[i]); rm.recive(msgs[i],i);; } }
}
Android使用javamail收发邮件