基於需求需要從郵件里讀取附件,從網絡搜索整理如下:
1 使用 Spire.Email
從官網下載安裝並引用,地址:https://www.e-iceblue.com/Download/email-for-net.html
獲取附件代碼如下:
using System.IO; using Spire.Email.Pop3; //添加命名空間 // Create a POP3 client and connect. Pop3Client client = new Pop3Client(); client.Host = Host; client.Username = Username; client.Password = Password; client.Port = 110; client.EnableSsl = false; client.Connect(); Spire.Email.MailMessage message = client.GetMessage(1); //下載附件 foreach (Spire.Email.Attachment attach in message.Attachments) { // To get and save the attachment string filePath = "d:\\"+ + attach.ContentType.Name; if (File.Exists(filePath)) { File.Delete(filePath); } //FileStream fs = File.Create(filePath); CopyStream(attach.Data, filePath); } private void CopyStream(Stream input, string filePath) { FileStream fs = null; try { fs = File.Create(filePath); byte[] buffer = new byte[8 * 1024]; int len; while ((len = input.Read(buffer, 0, buffer.Length)) > 0) { fs.Write(buffer, 0, len); } fs.Close(); } catch (Exception) { if (fs != null) { fs.Close(); } throw; } }
當做成服務循環執行的時候發現過段時間就報一次錯,不知道是不是因為付費的原因,所以棄用尋找下一個庫
2 使用 LumiSoft.Net
下載地址:http://www.lumisoft.ee/lswww/download/downloads/ 或者通過 NuGet程序包搜索下載
獲取附件代碼如下:
1 using System.IO; 2 using LumiSoft.Net; 3 using LumiSoft.Net.Log; 4 using LumiSoft.Net.POP3.Client; 5 using LumiSoft.Net.MIME; 6 using LumiSoft.Net.Mail; 7 8 9 POP3_Client pop3 = new POP3_Client(); 11 pop3.Connect(Host, Port, false); 12 pop3.Login(UserName, Pwd);//兩個參數,前者為Email的賬號,后者為Email的密碼 15 POP3_ClientMessageCollection messages = pop3.Messages; 17 if (messages.Count <= 0) 18 { 19 return; 20 } 21 POP3_ClientMessage message = messages[0];//轉化為POP3 22 23 byte[] messageBytes = message.MessageToByte(); 24 Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes); 25 26 MIME_Entity[] attachments = mime_message.GetAttachments(true, true); 27 28 foreach (MIME_Entity entity in attachments) 29 { 30 if (entity.ContentDisposition != null) 31 { 32 string fileName = entity.ContentDisposition.Param_FileName; 33 if (!string.IsNullOrEmpty(fileName)) 34 { 35 DirectoryInfo dir = new DirectoryInfo(@"D:\email\"); 36 if (!dir.Exists) dir.Create(); 37 38 string path = Path.Combine(dir.FullName, fileName); 39 MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body; 40 Stream decodedDataStream = byteObj.GetDataStream(); 41 using (FileStream fs = new FileStream(path, FileMode.Create)) 42 { 43 LumiSoft.Net.Net_Utils.StreamCopy(decodedDataStream, fs, 4000); 44 }46 } 47 } 48 } 49 message.MarkForDeletion(); 52 pop3.Disconnect();
還有其它的庫沒用過不做記錄
記錄供日后參考