最開始查詢資料的時候遇到很多問題,不是POP無法讀取就是不報錯也拿不到郵件。
后面接觸到S22.Imap.dll,巴適的很喲。郵件文本and附件全部拿到手。想如何就如何。
首先最基本的四大參數:地址、端口、賬戶、密碼
其次得熟知ImapClient,這個類用於打開你與郵箱之間的連接。
緊接着你就會接觸到uint,每封郵件都有一個uid ,通過uid你才可以拿到文本以及附件。
msg.Attachments//拿到該郵件附件的集合
msg.AlternateViews//拿到該郵件文本的集合
拿到文本和附件都可以開始你后續想做的事情了,操作文本和附件的時候多多少少都會用到IO,溫馨提醒別忘記關閉了喲。
每操作一封郵件之后也別忘了更新當前郵件的狀態喲
client.SetMessageFlags(uid, null, S22.Imap.MessageFlag.Seen);
代碼如下,需要自提。如有疑問可以提出。
public ContentResult CaptureMail() { StringBuilder strbFileErrorMsg = new StringBuilder(); #region 讀取郵件 string url = @"D:\SpainFile\ZIP";//D:\SpainFile\ZIP 郵件ZIP 保存目錄 string host = ""; int port = 143; string username = ""; string password = ""; using (S22.Imap.ImapClient client = new S22.Imap.ImapClient(host, port, username, password)) { //client.Search(S22.Imap.SearchCondition.Unseen(),null); var unseen = client.Search(S22.Imap.SearchCondition.Unseen(), null); if (unseen == null || unseen.Count() == 0) { strbFileErrorMsg.Append("==============>沒有新郵件!\n"); } Console.WriteLine(string.Format("==============>開始檢測\n")); foreach (uint uid in unseen) { var msg = client.GetMessage(uid, true, null); try { foreach (var item in msg.Attachments) { string filename = item.Name.Substring(item.Name.Length - 4 >= 0 ? item.Name.Length - 4 : 0); if (filename.Substring(filename.IndexOf(".") + 1).ToUpper() == "ZIP") { FileStream fs = new FileStream(url + @"\" + item.Name, FileMode.Create, FileAccess.Write); item.ContentStream.CopyTo(fs); item.ContentStream.Close(); fs.Close(); } } client.SetMessageFlags(uid, null, S22.Imap.MessageFlag.Seen); } catch (Exception ex) { strbFileErrorMsg.Append("讀取郵件<e-mail>" + msg.AlternateViews[0].ContentStream.ToString() + @"<\e-mail>失敗\n"); throw ex; } } } StreamWriter sw = new StreamWriter(@"D:\SpainFile\ErrorMsgFile\" + DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".TXT", false, Encoding.Default);//實例化StreamWriter sw.WriteLine(strbFileErrorMsg.ToString()); sw.Close(); #endregion return Content("抓取成功,時間為:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); }
