Android裏訪問網絡、收發短信都仍是常常用到的功能,可是此次需求是能夠收發郵件,網上搜了下,這裏轉一個,博主寫的幾個工具類確實很是好用,轉帖過來,下面是須要用到的資源和工具類文件html
http://pan.baidu.com/s/1hqejT7Ajava
在發送多用戶郵件中我添加了發送帶附件的郵件的代碼android
1 發送郵件服務器
今天學習了一下JavaMail,javamail發送郵件確實是一個比較麻煩的問題不用第三方郵件程序。爲了之後使用方便,本身寫了段代碼.網絡
Javamail-Android配置步驟:session
下載Android版本JavaMail包,additional.jar、mail.jar和activation.jar,下載地址JavaMail-Androidapp
在項目與src同一目錄級別下,新建文件夾lib,將下載的3個jar包放入該文件夾工具
右鍵->Properties->Java Build Path->Libraries,選擇Add External JARs,找到項目下lib目錄的3個jar包post
個人代碼有三個類:
第一個類:MailSenderInfo.java學習
01 package com.util.mail; 02 /** 03
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
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);//發送抄送 最後,給出朋友們幾個注意的地方:
一、使用此代碼你能夠完成你的javamail的郵件發送功能、發多個郵箱。三個類缺一不可。
二、這三個類我打包是用的com.util.mail包,若是不喜歡,你能夠本身改,但三個類文件必須在同一個包中
三、不要使用你剛剛註冊過的郵箱在程序中發郵件,若是你的163郵箱是剛註冊不久,那你就不要使用「smtp.163.com」。由於你發不出去。剛註冊的郵箱是不會給你這種權限的,也就是你不能經過驗證。要使用你常常用的郵箱,並且時間比較長的。
四、另外一個問題就是mailInfo.setMailServerHost("smtp.163.com");與mailInfo.setFromAddress("xxx@163.com");這兩句話。即若是你使用163smtp服務器,那麼發送郵件地址就必須用163的郵箱,若是不的話,是不會發送成功的。
五、關於javamail驗證錯誤的問題,網上的解釋有不少,但我看見的只有一個。就是個人第三個類。你只要複製全了代碼,我想是不會有問題的。
六、 而後在Android項目中添加網絡訪問權限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
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);; } }
}