最开始查询资料的时候遇到很多问题,不是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")); }
