javamail收發(fā)郵件(帶附件,正文帶圖)_第1頁
javamail收發(fā)郵件(帶附件,正文帶圖)_第2頁
javamail收發(fā)郵件(帶附件,正文帶圖)_第3頁
javamail收發(fā)郵件(帶附件,正文帶圖)_第4頁
javamail收發(fā)郵件(帶附件,正文帶圖)_第5頁
已閱讀5頁,還剩15頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、1. 郵件1.1 郵件組成部分如果是新郵件就獲取,并解析它;郵件是由郵件頭和郵件體組成,在郵件頭中主要包含了收件人、發(fā)件人、主題等等基礎(chǔ)信息。而郵件體中就包括了郵件的正文和附件等內(nèi)容信息。下圖就是pop3協(xié)議下,郵件的大致內(nèi)容。1.2 發(fā)送郵件(帶附件、正文帶圖片)QQ郵箱為例: 需要QQ賬號(hào)和QQ登錄第三方客戶端時(shí),密碼框的“授權(quán)碼”(相當(dāng)于密碼)授權(quán)碼如下獲?。捍a如下:public class JavaMailboxAttachment private MimeMessage message; private Session session; private String mailHos

2、t = "" private String mailAuth = "" private String mailPort = "" private String sender_username = ""private String sender_password = ""/定義一個(gè)Properties 用于存放信息 private Properties properties = new Properties(); /-發(fā)信箱-public JavaMailboxAttachment(String

3、email_type) try properties.put("mail.smtp.host",""); /發(fā)送郵件服務(wù)器 /端口號(hào),QQ郵箱給出了兩個(gè)端口,但是另一個(gè)我一直使用不了,所以就給出這一個(gè)587 properties.put("mail.smtp.port", "587"); /發(fā)送郵件端口號(hào) properties.put("mail.smtp.auth", "true"); / 此處填寫你的賬號(hào) properties.put("mail.user&qu

4、ot;, "xxxxxxxxx"); / 此處的密碼就是前面說的16位STMP授權(quán)碼 properties.put("mail.password", "xxxxxxxxxxxxxxxx"); this.mailHost = properties.getProperty("mail.smtp.host"); this.mailAuth = properties.getProperty("mail.smtp.auth"); this.mailPort = properties.getProperty

5、("mail.smtp.port"); this.sender_username = properties.getProperty("mail.user"); this.sender_password = properties.getProperty("mail.password"); catch (Exception e) e.printStackTrace(); / 構(gòu)建授權(quán)信息,用于進(jìn)行SMTP進(jìn)行身份驗(yàn)證 Authenticator authenticator = new Authenticator() protected P

6、asswordAuthentication getPasswordAuthentication() / 用戶名、密碼 String userName = properties.getProperty("mail.user"); String password = properties.getProperty("mail.password"); return new PasswordAuthentication(userName, password); ; session = Session.getInstance(properties,authentic

7、ator); /用戶驗(yàn)證 message = new MimeMessage(session); /將驗(yàn)證成功的session信息,創(chuàng)建一個(gè)message 對(duì)象。 /* * 發(fā)送郵件 * param subject * 郵件主題 * param sendHtml * 郵件內(nèi)容 * param receiveUser * 收件人地址 * param file * 附件 */ public int doSendHtmlEmail(String subject, String sendHtml, String receiveUser, Vector file) try / 發(fā)件人 InternetA

8、ddress from = new InternetAddress(sender_username); message.setFrom(from); / 收件人 InternetAddress to = new InternetAddress(receiveUser); message.setRecipient(Message.RecipientType.TO, to); / 郵件主題 message.setSubject(subject); / 向multipart對(duì)象中添加郵件的各個(gè)部分內(nèi)容,包括文本內(nèi)容帶圖片和附件 BodyPart contentPart = new MimeBodyP

9、art(); Multipart multipart = new MimeMultipart("related"); /用于來關(guān)聯(lián)文本內(nèi)容中圖片。 / 添加郵件正文 String imgaeString=Qh_method.randNumID("qunhong_"); /生成一個(gè)隨機(jī)數(shù),大家可以自己寫 multipart.addBodyPart(contentPart);/利用正則找出圖片中的src改成cid final Pattern imgRegExp = Ppile( "<img>+srcs*=s*'"(&#

10、39;"+)'">*>" ); Map<String, String> inlineImage = new HashMap<String, String>(); final Matcher matcher = imgRegExp.matcher( sendHtml ); int i = 0; while ( matcher.find() ) String src = matcher.group(); if ( sendHtml.indexOf( src ) != -1 ) String srcToken = "

11、src="" int x = src.indexOf( srcToken ); int y = src.indexOf( """, x + srcToken.length() ); String srcText = src.substring( x + srcToken.length(), y ); String Sub = srcText.substring(srcText.indexOf("."),srcText.length(); String cid = imgaeString + i; String newSrc

12、= src.replace( srcText, "cid:" + cid +Sub); inlineImage.put( cid, srcText.split( "," )0 ); sendHtml = sendHtml.replace( src, newSrc ); i+; /這里說明一下為什么要將正文里的圖片轉(zhuǎn)為cid,個(gè)人理解:附件和正文里的圖片都?xì)w于附件傳輸,設(shè)置cid用于識(shí)別附件是否為正文底下圖片。/修改后正文內(nèi)容放置contentPart contentPart.setContent(sendHtml, "text/html;cha

13、rset=UTF-8"); /獲取項(xiàng)目路徑,來獲得正文底下的圖片,上傳至服務(wù)器。String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile(); int indexOf = path.indexOf("xxxxxxxxx"); path=path.substring(0,indexOf); for (int j = 0; j < inlineImage.size(); j+) MimeBodyPart jpgBody = new MimeB

14、odyPart(); FileDataSource fds = new FileDataSource(path+inlineImage.get(imgaeString+j); jpgBody.setDataHandler(new DataHandler(fds); jpgBody.setContentID(imgaeString+j); /必須與cid一樣 String Sub = inlineImage.get(imgaeString+j).substring(inlineImage.get(imgaeString+j).indexOf("."),inlineImage.

15、get(imgaeString+j).length(); jpgBody.setFileName(MimeUtility.encodeWord(imgaeString+j+Sub); multipart.addBodyPart(jpgBody); / 添加附件的內(nèi)容 if(!file.isEmpty()/有附件 Enumeration efile=file.elements(); while(efile.hasMoreElements() BodyPart attachmentBodyPart = new MimeBodyPart(); String file_name=efile.nextE

16、lement().toString(); /選擇出每一個(gè)附件名 FileDataSource fds=new FileDataSource(file_name); /得到數(shù)據(jù)源 attachmentBodyPart.setDataHandler(new DataHandler(fds); /得到附件本身并至入BodyPart attachmentBodyPart.setFileName(MimeUtility.encodeWord(fds.getName(); /得到文件名同樣至入BodyPart multipart.addBodyPart(attachmentBodyPart); file.

17、removeAllElements(); / 將multipart對(duì)象放到message中 message.setContent(multipart); / 保存郵件 long start=System.currentTimeMillis(); / 發(fā)送 Transport.send(message); System.out.println("send success!"); long end=System.currentTimeMillis(); System.out.println("發(fā)送郵箱使用了"+(end-start)/1000); catch

18、 (Exception e) e.printStackTrace(); return 0; finally return 1; public static void main(String args) throws Exception Vector file_Vector = new Vector(); /存放文件的集合 file_Vector.add("D:/11.txt"); file_Vector.add("D:/22.txt"); JavaMailboxAttachment se = new JavaMailboxAttachment(email

19、_type); zt=se.doSendHtmlEmail(Mailbox_title,Text,receive_account,file); 1.3 接收郵件(帶附件、正文帶圖片)public class JavaMailboxAttachment private MimeMessage message; private Session session; private String mailHost = "" private String mailAuth = "" private String mailPort = "" pri

20、vate String sender_username = "" private String sender_password = "" private Properties properties = new Properties();private static String strSQL=""private String file_unique=""private String file_mc=""private HashMap<String,String> isMapImage

21、=new HashMap();private MimeMessage mimeMessage = null; public JavaMailboxAttachment(MimeMessage mimeMessage) this.mimeMessage = mimeMessage; /-收信箱- public JavaMailboxAttachment(String user_number,String user_password,String receive_name,String receive_account) try / 準(zhǔn)備連接服務(wù)器的會(huì)話信息 /不需要變 long start=Sys

22、tem.currentTimeMillis(); Properties props = new Properties(); props.setProperty("tocol", "imap"); props.setProperty("mail.imap.host", ""); props.setProperty("mail.imap.port", "143"); /* QQ郵箱需要建立ssl連接 */ props.setProperty("

23、;mail.imap.socketFactory.class", ".ssl.SSLSocketFactory"); props.setProperty("mail.imap.socketFactory.fallback", "false"); props.setProperty("mail.imap.starttls.enable","true"); props.setProperty("mail.imap.socketFactory.port", "9

24、93"); / 創(chuàng)建Session實(shí)例對(duì)象 Session session = Session.getInstance(props); URLName urln = new URLName("imap", "", 143, null,"xxxxxxxxx","xxxxxxxxxxxxxx"); / 創(chuàng)建IMAP協(xié)議的Store對(duì)象 Store store = session.getStore(urln); store.connect(); / 獲得收件箱 Folder folder = store.get

25、Folder("INBOX"); / 以讀寫模式打開收件箱 folder.open(Folder.READ_WRITE); Message messages_UnRead = folder.getMessages(folder.getMessageCount()-folder.getUnreadMessageCount()+1,folder.getMessageCount() ; /獲取未讀郵件的個(gè)數(shù) if(messages_UnRead.length!=0) Message messages= folder.getMessages(); for (Message mess

26、age : messages) JavaMailboxAttachment pmm = new JavaMailboxAttachment(MimeMessage) message); if(!pmm.isNew() /True 表示已讀 HashMap map=new HashMap(); /每次進(jìn)來將其設(shè)置為空 isMapImage.clear(); file_unique="" file_mc="" map.put("receive_account", receive_account); map.put("receiv

27、e_name", receive_name); /保存所有附件(包括正文的圖片) map=saveAttachMent(Part)message,map); map.put("file_unique", file_unique); map.put("file_mc", file_mc); /獲取地址,發(fā)件人 map=getMailContent(message,map); /獲取正文 map=getMailTextContent(message,map); /標(biāo)記為已讀 message.setFlag(Flags.Flag.SEEN, true

28、); int zt = 0; long end=System.currentTimeMillis(); System.out.println("發(fā)送郵箱使用了"+(end-start)/1000); / 解析郵件 / 關(guān)閉資源 folder.close(false); store.close(); catch (Exception e) e.printStackTrace(); /* * 將附件和正文圖片保存置本地 */public HashMap saveAttachMent(Part part,HashMap map) throws Exception String i

29、ds=""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 disposition = mpart.getDisposition();/判斷是否是附件if (disposition != null) &&

30、(disposition.equals(Part.ATTACHMENT) | (disposition.equals(Part.INLINE) fileName = mpart.getFileName();if (fileName.toLowerCase().indexOf("gb2312") != -1|fileName.toLowerCase().indexOf("utf") != -1)fileName = MimeUtility.decodeText(fileName);if(fileName.indexOf("=?")>

31、;=0&&fileName.indexOf("?=")>=0)fileName=fileName.substring(fileName.indexOf("=?"),fileName.lastIndexOf("?=")+2);fileName=MimeUtility.decodeText(fileName);String isCid="" /區(qū)別附件與正文圖片地方try if(!mpart.getHeader("Content-ID")0.equals(""

32、;)isCid=mpart.getHeader("Content-ID")0.replace("<", "").replace(">", ""); catch (Exception e) String path =GetPath(); if(fileName.indexOf("qunhong_")!=-1) saveFile(fileName, mpart.getInputStream();else if(!isCid.equals("")St

33、ring subString=fileName.substring(fileName.indexOf("."), fileName.length();saveFile(fileName, mpart.getInputStream();renameFile(path+fileName,path+isCid+subString); isMapImage.put(isCid,isCid+subString);else String img_name=Qh_method.randNumID("img"); String subString=fileName.su

34、bstring(fileName.indexOf("."), fileName.length(); /更改文件名 saveFile(fileName, mpart.getInputStream(); renameFile(path+fileName,path+img_name+subString); file_unique+="/File_all/record_mail/"+img_name+subString+"," file_mc+=fileName+"," else if (mpart.isMimeType(

35、"multipart/*") saveAttachMent(mpart,map); else /QQ正文圖片獲取處 /這里QQ的正文圖片比較特殊需要這里獲取,下載至本地fileName = mpart.getFileName();if (fileName != null) if(fileName.indexOf("=?")>=0&&fileName.indexOf("?=")>=0)fileName=fileName.substring(fileName.indexOf("=?"),fi

36、leName.lastIndexOf("?=")+2);fileName=MimeUtility.decodeText(fileName); saveFile(fileName, mpart.getInputStream(); else if (part.isMimeType("message/rfc822") saveAttachMent(Part) part.getContent(),map);return map;private void saveFile(String fileName, InputStream is) try String pa

37、th = GetPath(); FileOutputStream fos = new FileOutputStream(path+fileName); int len = 0; byte bys = new byte1024; while (len = is.read(bys) != -1) fos.write(bys,0,len); fos.close(); catch (Exception e) e.printStackTrace(); private String GetPath() /獲取絕對(duì)路徑String path = this.getClass().getProtectionDo

38、main().getCodeSource().getLocation().getFile(); int indexOf = path.indexOf("WEB-INF"); path=path.substring(0,indexOf)+"File_all/record_mail/"return path;/* * 解析綜合數(shù)據(jù) * param part * param map2 * throws Exception */ private HashMap getMailContent(Message msg,HashMap map) throws Exce

39、ption Address froms = msg.getFrom(); if(froms != null) /System.out.println("發(fā)件人信息:" + froms0); InternetAddress addr = (InternetAddress)froms0; map.put("sent_account", addr.getAddress(); map.put("sent_name", addr.getPersonal(); map.put("mailbox_title",msg.getSu

40、bject(); /* Multipart o = (Multipart) msg.getContent(); */ return map; /* * 獲得郵件文本內(nèi)容 * param part 郵件體 * param map 存儲(chǔ)郵件文本內(nèi)容的字符串 * return * throws MessagingException * throws IOException */ public HashMap getMailTextContent(Part part, HashMap map) throws MessagingException, IOException /如果是文本類型的附件,通過g

41、etContent方法可以取到文本內(nèi)容,但這不是我們需要的結(jié)果,所以在這里要做判斷 boolean isContainTextAttach = part.getContentType().indexOf("name") > 0; if (part.isMimeType("text/*") && !isContainTextAttach) /循環(huán)Map存在則替換 /需要將正文中cid置換成src路徑 String path = GetPathRelation(); System.out.println(part.getContent(

42、).toString(); String pictureContent=part.getContent().toString().replace("cid:",path); Iterator ite=isMapImage.entrySet().iterator(); while(ite.hasNext() Entry string=(Entry)ite.next(); System.out.println(string.getKey().toString(); System.out.println(string.getValue().toString(); pictureC

43、ontent=pictureContent.replace(string.getKey().toString(),string.getValue().toString(); System.out.println(pictureContent); map.put("text", pictureContent); else if (part.isMimeType("message/rfc822") getMailTextContent(Part)part.getContent(),map); else if (part.isMimeType("multip

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論