C#.NET實現(xiàn)基于Lumisoft的郵件收發(fā)功能
最近因為不是太忙,所以就心血來潮的用Lumisoft寫了個Web端的郵件收發(fā)系統(tǒng)。在此記錄開發(fā)歷程。 一、首先先介紹下這個系統(tǒng)的基本思路:把郵件從服務器下載下來然后保存到本地,查看郵件的時候再加載郵件信息。這里,都是用XML,來存儲郵件的基本信息。 二、用到的類 Mail_Item類記錄郵件的基本信息 Person類記錄的是郵件用戶名及名稱 Attachment 類記錄附件的基本信息 Mail_Summary 郵件信息概要類,用于顯示郵件列表 User 用戶信息類,記錄用戶信息 /// <summary> /// 郵件的基本信息 /// </summary> public class Mail_Item { /// <summary> /// The unique mail Identity in Mail Server /// </summary> public string Mail_Id { get; set; } /// <summary> /// Mail sender /// </summary> public Person Mail_From { get; set; } /// <summary> /// Mail Receiver /// </summary> public List<Person> Mail_To = new List<Person>(); /// <summary> /// Mail copy to /// </summary> public List<Person> Mail_CopyTo = new List<Person>(); public string Mail_Subject { get; set; } /// <summary> /// Mail content path in localhost /// </summary> public string Mail_Body { get; set; } /// <summary> /// Mail receive date /// </summary> public string Mail_Date { get; set; } /// <summary> /// Mail attachments /// </summary> public List<Attachment> Mail_Attachment = new List<Attachment>(); /// <summary> /// mail is read or unread /// </summary> public bool IsRead { get; set; } public bool IsDeleted { get; set; } } 三、接收郵件 主要步驟有:登錄服務器-->判斷當前郵件在系統(tǒng)中是否已經(jīng)存在了->下載郵件,并且保存郵件的基本信息 接收郵件代碼: public static List<Mail_Item> ReceiveMail(User user, out int mailNum) { string baseBodyPath = @"Mails\" + user.Server + @"\" + user.Identity + @"\Mails\"; string baseAttPath = @"Mails\" + user.Server + @"\" + user.Identity + @"\Attachments\"; CreateFoder(user); mailNum = 0; string _mailServer = user.Server; string _isHelpAccount = user.Account; string _isHelpPassword = user.Password; List<Mail_Item> mails = new List<Mail_Item>(); if (string.IsNullOrEmpty(_mailServer) ││ string.IsNullOrEmpty(_isHelpAccount) ││ string.IsNullOrEmpty(_isHelpPassword)) { return mails; } string _mailId = string.Empty; string _subject = string.Empty; //主題 string _body = string.Empty; //正文 string _receiveDate = string.Empty;//接收時間 // Int64 maxUID = GetXmkUserInfo(_mailServer, _isHelpAccount, _isHelpPassword).MaxMailID; //獲取上一次接收郵件最大的ID //if (maxUID < 0) //{ // return mails; //} using (POP3_Client pop = new POP3_Client()) { try { pop.Connect(_mailServer, 110, false); pop.Login(_isHelpAccount, _isHelpPassword); POP3_ClientMessageCollection messages = pop.Messages; //1415170251.6684.Qmail,S=866235:第一部分是遞增的 //最后一份郵件都不是最新的,要提示 // _mailId = messages[messages.Count - 1].UID; for (int i = messages.Count - 1; 0 <= i; i--) { _mailId = messages[i].UID; //try //{ // byte[] bt = messages[i].HeaderToByte(); // Mail_Message mime_header = Mail_Message.ParseFromByte(bt); // Mail_h_Received[] r = mime_header.Received; //} //catch //{ } //if (Convert.ToInt64(_mailId.Split('.')[0]) <= maxUID) // return mails; try { if (CheckMailExists(user, _mailId)) //如果存在 { continue; } } catch { ; } #region 讀取郵件 POP3_ClientMessage ms = messages[i]; if (ms != null) { List<Person> p_to = new List<Person>(); //收件人列表 List<Person> p_copyTo = new List<Person>();//抄送人列表 Person p_from = new Person();//發(fā)送人 List<Attachment> list_att = new List<Attachment>();//附件信息 #region 基本信息 //有新郵件就+1 Mail_Message mime_message = new Mail_Message(); try { byte[] messageBytes = ms.MessageToByte(); mime_message = Mail_Message.ParseFromByte(messageBytes); } catch { continue; } mailNum++; try { _subject = mime_message.Subject.Trim() == string.Empty ? "No Subject" : mime_message.Subject; } catch (Exception ex) { _subject = "No Subject"; } p_from.Address = mime_message.From == null ? "sender is null" : mime_message.From[0].Address; try { string name = ""; if (string.IsNullOrEmpty(mime_message.From[0].DisplayName)) { int index = mime_message.From[0].Address.IndexOf("@"); name = mime_message.From[0].Address.Substring(0, index); } else { name = mime_message.From[0].DisplayName; } p_from.Name = name; } catch (Exception fe) { p_from.Name = "SomeOne"; } try { Mail_t_AddressList to = mime_message.To; if (to.Count > 0 && to != null) { for (int ii = 0; ii < to.Mailboxes.Length; ii++) { string t_name = ""; if (string.IsNullOrEmpty(to.Mailboxes[ii].DisplayName)) { int index = to.Mailboxes[ii].Address.IndexOf("@"); t_name = to.Mailboxes[ii].Address.Substring(0, index); } else { t_name = to.Mailboxes[ii].DisplayName; } Person per = new Person { Address = to.Mailboxes[ii].Address, Name = t_name }; p_to.Add(per); } } } catch (Exception e) { ; } try { Mail_t_AddressList copyTo = mime_message.Cc; //獲取的抄送人信息 if (copyTo.Count > 0 && copyTo != null) { for (int ii = 0; ii < copyTo.Mailboxes.Length; ii++) { string t_name = ""; if (string.IsNullOrEmpty(copyTo.Mailboxes[ii].DisplayName)) { int index = copyTo.Mailboxes[ii].Address.IndexOf("@"); t_name = copyTo.Mailboxes[ii].Address.Substring(0, index); } else { t_name = copyTo.Mailboxes[ii].DisplayName; } Person per1 = new Person { Address = copyTo.Mailboxes[ii].Address, Name = t_name }; p_copyTo.Add(per1); } } } catch (Exception e) { ; } try { _receiveDate = mime_message.Date.ToString("yyyy-MM-dd HH:mm:ss"); } catch { Mail_h_Received[] r = mime_message.Received; _receiveDate = r[0].Time.ToString("yyyy-MM-dd HH:mm:ss") ; } _body = mime_message.BodyText; try { if (!string.IsNullOrEmpty(mime_message.BodyHtmlText)) { _body = mime_message.BodyHtmlText; } } catch { _body = mime_message.BodyText; ;//Response.Write("<script>alert('HTMLBODY');</script>");//屏蔽編碼出現(xiàn)錯誤的問題,錯誤在BodyText存在而BodyHtmlText不存在的時候,訪問BodyHtmlText會出現(xiàn) } #endregion #region 附件信息 MIME_Entity[] attachments = mime_message.GetAttachments(true, true); foreach (MIME_Entity entity in attachments) { Attachment m_att = new Attachment(); string cid; int eIndex; if (entity.ContentDisposition != null) //不是內(nèi)嵌附件 { cid = entity.ContentID; string _aName = entity.ContentDisposition.Param_FileName;//區(qū)別物理名和邏輯 m_att.A_ID = System.Guid.NewGuid().ToString(); if (string.IsNullOrEmpty(_aName)) { // _aName = entity.ContentDisposition.Parameters.Owner.ValueToString(); _aName = entity.ContentDescription.ToString(); } m_att.Name = _aName; //_attName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + m_att.A_ID; string type = entity.ContentType.ValueToString(); if (!string.IsNullOrEmpty(m_att.Name)) { string path = Path.Combine(baseAttPath, m_att.A_ID + "_" + m_att.Name); m_att.Path = path; try { MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body; Stream decodedDataStream = byteObj.GetDataStream(); using (FileStream fs = new FileStream(serverPath+ path, FileMode.Create)) { try { LumiSoft.Net.Net_Utils.StreamCopy(decodedDataStream, fs, 4000); } catch (Exception e) { ; } } } catch (Exception e) { ; } } m_att.IsInline = entity.ContentDisposition.DispositionType == MIME_DispositionTypes.Inline; } else //內(nèi)嵌附件 { cid = entity.ContentID; m_att.A_ID = System.Guid.NewGuid().ToString(); m_att.Name = entity.ContentType.Parameters["name"]; try { eIndex = m_att.Name.LastIndexOf(".");//有些圖片沒有后綴名,直接添加一個后綴 if (eIndex == -1) m_att.Name += ".png"; } catch (Exception e) { m_att.Name = System.Guid.NewGuid().ToString() + ".png"; } string path = Path.Combine(baseAttPath, m_att.A_ID + "_" + m_att.Name); m_att.Path = path; string enString = entity.ToString(); int a = enString.LastIndexOf(">"); string base64string = enString.Substring(a + 5); byte[] bt = Convert.FromBase64String(base64string); File.WriteAllBytes(serverPath+m_att.Path, bt); m_att.IsInline = true; } m_att.ContentID = entity.ContentID; try { if (cid != null ││ cid.Trim() != string.Empty) _body = _body.Replace("cid:" + cid.Substring(1, cid.Length - 2), m_att.Path); } catch (Exception e) { ; } list_att.Add(m_att); } #endregion //Body內(nèi)容存儲為一個文件 string _bodyFileName = System.Guid.NewGuid().ToString() + ".html"; try { File.WriteAllText(serverPath+ baseBodyPath + _bodyFileName, _body,Encoding.GetEncoding("utf-8")); // File.w } catch { ; } Mail_Item mi = new Mail_Item { Mail_Id = _mailId, Mail_From = p_from, Mail_To = p_to, Mail_CopyTo = p_copyTo, Mail_Subject = _subject, Mail_Body = baseBodyPath + _bodyFileName, Mail_Attachment = list_att, Mail_Date = _receiveDate, IsRead = false, IsDeleted = false }; mails.Add(mi); #endregion } } } catch (Exception e) { ; } pop.Disconnect(); return mails; } } 在接收郵件中不得不提的是郵件內(nèi)嵌圖片的接收,內(nèi)嵌圖片不像普通附件那樣,它的entity.ContentDisposition=null,所以得另行討論,見代碼。還有一個關于附件的問題是我用hotmail給我的qq郵箱發(fā)的附件,它的entity.ContentDisposition.Param_FileName為null,所以我做了如下處理 string _aName = entity.ContentDisposition.Param_FileName;//區(qū)別物理名和邏輯 m_att.A_ID = System.Guid.NewGuid().ToString(); if (string.IsNullOrEmpty(_aName)) { // _aName = entity.ContentDisposition.Parameters.Owner.ValueToString(); _aName = entity.ContentDescription.ToString(); } 自此基本的郵件接收就沒問題了。 以下是我寫的郵件系統(tǒng)截圖: 項目地址Web 郵件系統(tǒng) 附件:C#.NET實現(xiàn)基于Lumisoft的郵件收發(fā)功能.rar 該文章在 2019/8/8 11:13:03 編輯過 |
關鍵字查詢
相關文章
正在查詢... |