版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、以下為Mail.java的全部代碼:/* * 該類使用Socket連接到郵件服務器, * 并實現(xiàn)了向指定郵箱發(fā)送郵件及附件的功能。 * * author Zhong Lizhi */public class Mail /* * 換行符 */ private static final String LINE_END = "rn" /* * 值為“true”輸出高度信息(包括服務器響應信息),值為“ * false”則不輸出調試信息。 */ private boolean isDebug = true; /* * 值為“true”則在發(fā)送郵件link Mail#send() *
2、 過程中會讀取服務器端返回的消息, * 并在郵件發(fā)送完畢后將這些消息返回給用戶。 */ private boolean isAllowReadSocketInfo = true; /* * 郵件服務器地址 */ private String host; /* * 發(fā)件人郵箱地址 */ private String from; /* * 收件人郵箱地址 */ private List<String> to; /* * 抄送地址 */ private List<String> cc; /* * 暗送地址 */ private List<String> bcc;
3、/* * 郵件主題 */ private String subject; /* * 用戶名 */ private String user; /* * 密碼 */ private String password; /* * MIME郵件類型 */ private String contentType; /* * 用來綁定多個郵件單元link #partSet * 的分隔標識,我們可以將郵件的正文及每一個附件都看作是一個郵件單元 * 。 */ private String boundary; /* * 郵件單元分隔標識符,該屬性將用來在郵件中作為分割各個郵件單元的標識 * 。 */ private
4、 String boundaryNextPart; /* * 傳輸郵件所采用的編碼 */ private String contentTransferEncoding; /* * 設置郵件正文所用的字符集 */ private String charset; /* * 內容描述 */ private String contentDisposition; /* * 郵件正文 */ private String content; /* * 發(fā)送郵件日期的顯示格式 */ private String simpleDatePattern; /* * 附件的默認MIME類型 */ private Str
5、ing defaultAttachmentContentType; /* * 郵件單元的集合,用來存放正文單元和所有的附件單元。 */ private List<MailPart> partSet; /* * 不同類型文件對應的link MIME 類型映射。在添加附件 * link #addAttachment(String) * 時,程序會在這個映射中查找對應文件的 link MIME * 類型,如果沒有, 則使用 * link #defaultAttachmentContentType * 所定義的類型。 */ private static Map<String, Str
6、ing> contentTypeMap; static / MIME Media Types contentTypeMap = new HashMap<String, String>(); contentTypeMap.put("xls", "application/vnd.ms-excel"); contentTypeMap.put("xlsx", "application/vnd.ms-excel"); contentTypeMap.put("xlsm", "ap
7、plication/vnd.ms-excel"); contentTypeMap.put("xlsb", "application/vnd.ms-excel"); contentTypeMap.put("doc", "application/msword"); contentTypeMap.put("dot", "application/msword"); contentTypeMap.put("docx", "application/
8、msword"); contentTypeMap.put("docm", "application/msword"); contentTypeMap.put("dotm", "application/msword"); /* * 該類用來實例化一個正文單元或附件單元對象,他繼承了 * link Mail * ,在這里制作這個子類主要是為了區(qū)別郵件單元對象和郵件服務對象 * ,使程序易讀一些。 這些郵件單元全部會放到partSet * 中,在發(fā)送郵件 link #send()時, 程序會調用 * link
9、#getAllParts() * 方法將所有的單元合并成一個符合MIME格式的字符串。 * * author Zhong Lizhi */ private class MailPart extends Mail public MailPart() /* * 默認構造函數(shù) */ public Mail() defaultAttachmentContentType = "application/octet-stream" simpleDatePattern = "yyyy-MM-dd HH:mm:ss" boundary = "-=_NextPar
10、t_zlz_3907_" + System.currentTimeMillis(); boundaryNextPart = "-" + boundary; contentTransferEncoding = "base64" contentType = "multipart/alternative" charset = Charset.defaultCharset().name(); partSet = new ArrayList<MailPart>(); to = new ArrayList<String
11、>(); cc = new ArrayList<String>(); bcc = new ArrayList<String>(); /* * 根據(jù)指定的完整文件名在 * link #contentTypeMap * 中查找其相應的MIME類型, 如果沒找到,則返回 * link #defaultAttachmentContentType * 所指定的默認類型。 * * param fileName * 文件名 * return 返回文件對應的MIME類型。 */ private String getPartContentType(String fileName)
12、String ret = null; if (null != fileName) int flag = fileName.lastIndexOf("."); if (0 <= flag && flag < fileName.length() - 1) fileName = fileName.substring(flag + 1); ret = contentTypeMap.get(fileName); if (null = ret) ret = defaultAttachmentContentType; return ret; /* * 將給定字
13、符串轉換為base64編碼的字符串 * * param str * 需要轉碼的字符串 * param charset * 原字符串的編碼格式 * return base64編碼格式的字符 */ private String toBase64(String str, String charset) if (null != str) try return toBase64(str.getBytes(charset); catch (UnsupportedEncodingException e) e.printStackTrace(); return "" /* * 將指定的字節(jié)
14、數(shù)組轉換為base64格式的字符串 * * param bs * 需要轉碼的字節(jié)數(shù)組 * return base64編碼格式的字符 */ private String toBase64(byte bs) return new BASE64Encoder().encode(bs); /* * 將給定字符串轉換為base64編碼的字符串 * * param str * 需要轉碼的字符串 * return base64編碼格式的字符 */ private String toBase64(String str) return toBase64(str, Charset.defaultCharset()
15、.name(); /* * 將所有的郵件單元按照標準的MIME格式要求合并。 * * return 返回一個所有單元合并后的字符串。 */ private String getAllParts() int partCount = partSet.size(); StringBuilder sbd = new StringBuilder(LINE_END); for (int i = partCount - 1; i >= 0; i-) Mail attachment = partSet.get(i); String attachmentContent = attachment.getCo
16、ntent(); if (null != attachmentContent && 0 < attachmentContent.length() sbd.append(getBoundaryNextPart().append(LINE_END); sbd.append("Content-Type: "); sbd.append(attachment.getContentType(); sbd.append(LINE_END); sbd.append("Content-Transfer-Encoding: "); sbd.append
17、(attachment.getContentTransferEncoding(); sbd.append(LINE_END); if (i != partCount - 1) sbd.append("Content-Disposition: "); sbd.append(attachment.getContentDisposition(); sbd.append(LINE_END); sbd.append(LINE_END); sbd.append(attachment.getContent(); sbd.append(LINE_END); sbd.append(LINE_
18、END); sbd.append(LINE_END); / sbd.append(boundaryNextPart). / append(LINE_END); partSet.clear(); return sbd.toString(); /* * 添加郵件正文單元 */ private void addContent() if (null != content) MailPart part = new MailPart(); part.setContent(toBase64(content); part.setContentType("text/plain;charset=&quo
19、t;" + charset + """); partSet.add(part); private String listToMailString(List<String> mailAddressList) StringBuilder sbd = new StringBuilder(); if (null != mailAddressList) int listSize = mailAddressList.size(); for (int i = 0; i < listSize; i+) if (0 != i) sbd.append(&q
20、uot;"); sbd.append("<").append(mailAddressList.get(i).append(">"); return sbd.toString(); private List<String> getrecipient() List<String> list = new ArrayList<String>(); list.addAll(to); list.addAll(cc); list.addAll(bcc); return list; /* * 添加一個附件單元 *
21、 * param filePath * 文件路徑 */ public void addAttachment(String filePath) addAttachment(filePath, null); public void addTo(String mailAddress) public void addCc(String mailAddress) public void addBcc(String mailAddress) /* * 添加一個附件單元 * * param filePath * 文件路徑 * param charset * 文件編碼格式 */ public void add
22、Attachment(String filePath, String charset) if (null != filePath && filePath.length() > 0) File file = new File(filePath); try addAttachment(file.getName(), new FileInputStream(file), charset); catch (FileNotFoundException e) System.exit(1); /* * 添加一個附件單元 * * param fileName * 文件名 * param
23、attachmentStream * 文件流 * param charset * 文件編碼格式 */ public void addAttachment(String fileName, InputStream attachmentStream, String charset) try byte bs = null; if (null != attachmentStream) int buffSize = 1024; byte buff = new bytebuffSize; byte temp; bs = new byte0; int readTotal = 0; while (-1 !=
24、(readTotal = attachmentStream.read(buff) temp = new bytebs.length; System.arraycopy(bs, 0, temp, 0, bs.length); bs = new bytetemp.length + readTotal; System.arraycopy(temp, 0, bs, 0, temp.length); System.arraycopy(buff, 0, bs, temp.length, readTotal); if (null != bs) MailPart attachmentPart = new Ma
25、ilPart(); charset = null != charset ? charset : Charset.defaultCharset() .name(); String contentType = getPartContentType(fileName) + "name="=?" + charset + "?B?" + toBase64(fileName) + "?="" attachmentPart.setCharset(charset); attachmentPart.setContentType(co
26、ntentType); attachmentPart.setContentDisposition("attachment;filename="=?" + charset + "?B?" + toBase64(fileName) + "?=""); attachmentPart.setContent(toBase64(bs); partSet.add(attachmentPart); catch (Exception e) e.printStackTrace(); finally if (null != attach
27、mentStream) try attachmentStream.close(); attachmentStream = null; catch (IOException e) e.printStackTrace(); Runtime.getRuntime().gc(); Runtime.getRuntime().runFinalization(); /* * 發(fā)送郵件 * * return 郵件服務器反回的信息 */ public String send() / 對象申明 / 當郵件發(fā)送完畢后,以下三個對象(Socket、 / PrintWriter, / BufferedReader)需要
28、關閉。 Socket socket = null; PrintWriter pw = null; BufferedReader br = null; try socket = new Socket(host, 25); pw = new PrintWriter(socket.getOutputStream(); br = new BufferedReader(new InputStreamReader(socket .getInputStream(); StringBuilder infoBuilder = new StringBuilder( "nServer info: n-n&
29、quot;); / 與服務器建立連接 pw.write("HELO ".concat(host).concat(LINE_END); / 連接到郵件服務 if (!readResponse(pw, br, infoBuilder, "220") return infoBuilder.toString(); pw.write("AUTH LOGIN".concat(LINE_END); / 登錄 if (!readResponse(pw, br, infoBuilder, "250") return infoBuil
30、der.toString(); pw.write(toBase64(user).concat(LINE_END); / 輸入用戶名 if (!readResponse(pw, br, infoBuilder, "334") return infoBuilder.toString(); pw.write(toBase64(password).concat(LINE_END); / 輸入密碼 if (!readResponse(pw, br, infoBuilder, "334") return infoBuilder.toString(); pw.writ
31、e("MAIL FROM:<" + from + ">" + LINE_END); / 發(fā)件人郵箱地址 if (!readResponse(pw, br, infoBuilder, "235") return infoBuilder.toString(); List<String> recipientList = getrecipient(); / 收件郵箱地址 for (int i = 0; i < recipientList.size(); i+) pw.write("RCPT TO:<
32、;" + recipientList.get(i) + ">" + LINE_END); if (!readResponse(pw, br, infoBuilder, "250") return infoBuilder.toString(); / getAllSendAddress(); pw.write("DATA" + LINE_END); / 開始輸入郵件 if (!readResponse(pw, br, infoBuilder, "250") return infoBuilder.toSt
33、ring(); flush(pw); / 設置郵件頭信息 StringBuffer sbf = new StringBuffer("From: <" + from + ">" + LINE_END); / 發(fā)件人 sbf.append("To: " + listToMailString(to) + LINE_END);/ 收件人 sbf.append("Cc: " + listToMailString(cc) + LINE_END);/ 收件人 sbf.append("Bcc: "
34、+ listToMailString(bcc) + LINE_END);/ 收件人 sbf.append("Subject: " + subject + LINE_END);/ 郵件主題 SimpleDateFormat sdf = new SimpleDateFormat(simpleDatePattern); sbf.append("Date: ").append(sdf.format(new Date(); sbf.append(LINE_END); / 發(fā)送時間 sbf.append("Content-Type: "); sb
35、f.append(contentType); sbf.append(""); sbf.append("boundary=""); sbf.append(boundary).append("""); / 郵件類型設置 sbf.append(LINE_END); sbf.append("This is a multi-part message in MIME format."); sbf.append(LINE_END); / 添加郵件正文單元 addContent(); / 合并所有單元,正文和附
36、件。 sbf.append(getAllParts(); / 發(fā)送 sbf.append(LINE_END).append(".").append(LINE_END); pw.write(sbf.toString(); readResponse(pw, br, infoBuilder, "354"); flush(pw); / QUIT退出 pw.write("QUIT" + LINE_END); if (!readResponse(pw, br, infoBuilder, "250") return infoBu
37、ilder.toString(); flush(pw); return infoBuilder.toString(); catch (Exception e) e.printStackTrace(); return "Exception:>" + e.getMessage(); finally / 釋放資源 try if (null != socket) socket.close(); if (null != pw) pw.close(); if (null != br) br.close(); catch (IOException e) e.printStackTr
38、ace(); /* * 將SMTP命令發(fā)送到郵件服務器 * * param pw * 郵件服務器輸入流 */ private void flush(PrintWriter pw) if (!isAllowReadSocketInfo) pw.flush(); /* * 讀取郵件服務器的響應信息 * * param pw * 郵件服務器輸入流 * param br * 郵件服務器輸出流 * param infoBuilder * 用來存放服務器響應信息的字符串緩沖 * param msgCode * return * throws IOException */ private boolean r
39、eadResponse(PrintWriter pw, BufferedReader br, StringBuilder infoBuilder, String msgCode) throws IOException if (isAllowReadSocketInfo) pw.flush(); String message = br.readLine(); infoBuilder.append("SERVER:/>"); infoBuilder.append(message).append(LINE_END); if (null = message | 0 >
40、message.indexOf(msgCode) pw.write("QUIT".concat(LINE_END); pw.flush(); return false; if (isDebug) return true; public String getBoundaryNextPart() return boundaryNextPart; public void setBoundaryNextPart(String boundaryNextPart) this.boundaryNextPart = boundaryNextPart; public String getDe
41、faultAttachmentContentType() return defaultAttachmentContentType; public void setDefaultAttachmentContentType( String defaultAttachmentContentType) this.defaultAttachmentContentType = defaultAttachmentContentType; public String getHost() return host; public void setHost(String host) this.host = host; public String getFrom() return from; public void setFrom(String from) this.from = from; public List<String> getTo() return to; public void setTo(List<String> to) this.to = to; pu
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 應急消防演練領導講話稿(6篇)
- 開學典禮活動總結范文15篇
- 愚人節(jié)文案(匯編15篇)
- 收銀培訓資料
- 中國電動汽車充電站行業(yè)政策、市場規(guī)模及投資前景研究報告(智研咨詢發(fā)布)
- 肝升肺降湯治療慢性腎衰竭升降失?;颊叩呐R床療效觀察
- 組合式長周期光纖光柵傳感器及其特性研究
- 二零二五年度家政服務與家庭寵物養(yǎng)護合同3篇
- 二零二五年度城市消防管網(wǎng)消火栓安裝施工協(xié)議3篇
- 無人機分群的任務分配與拓撲控制技術研究
- 蛋糕店服務員勞動合同
- 土地買賣合同參考模板
- 2025高考數(shù)學二輪復習-專題一-微專題10-同構函數(shù)問題-專項訓練【含答案】
- 新能源行業(yè)市場分析報告
- 2025年天津市政建設集團招聘筆試參考題庫含答案解析
- 2024-2030年中國烘焙食品行業(yè)運營效益及營銷前景預測報告
- 巖土工程勘察.課件
- 60歲以上務工免責協(xié)議書
- 康復醫(yī)院患者隱私保護管理制度
- 2022年7月2日江蘇事業(yè)單位統(tǒng)考《綜合知識和能力素質》(管理崗)
- 沈陽理工大學《數(shù)》2022-2023學年第一學期期末試卷
評論
0/150
提交評論