.NET接收邮件下载邮件附件——openpop.net

使用OpenPop.Net接收邮件很方便,下面是接收下载邮件附件的代码

OpenPop.Net下载地址 https://sourceforge.net/projects/hpop/

  1  public class EmailHelper
  2     {
  3         private string accout; //邮箱账户
  4         private string pass;//邮箱密码
  5         private string popServer; //pop服务地址(阿里云:pop3.mxhichina.com)
  6         private int popPort; //pop服务端口号(110)
  7         private bool isUseSSL;
  8 
  9         public EmailHelper(string _accout, string _pass, string _popServer, int _popPort, bool _isUseSSL)
 10         {
 11             this.accout = _accout;
 12             this.pass = _pass;
 13             this.popServer = _popServer;
 14             this.popPort = _popPort;
 15             this.isUseSSL = _isUseSSL;
 16         }
 17 
 18         #region 验证邮箱是否登录成功
 19         public bool ValidateAccount(ref string error)
 20         {
 21             Pop3Client client = new Pop3Client();
 22             try
 23             {
 24                 client.Connect(popServer, popPort, isUseSSL);
 25                 client.Authenticate(accout, pass);
 26             }
 27             catch (InvalidLoginException ex)
 28             {
 29                 error = "邮箱登录失败!";
 30                 return false;
 31             }
 32             catch (InvalidUseException ex)
 33             {
 34                 error = "邮箱登录失败!";
 35                 return false;
 36             }
 37             catch (PopServerNotFoundException ex)
 38             {
 39                 error = "服务器没有找到!";
 40                 return false;
 41             }
 42             catch (PopServerException ex)
 43             {
 44                 error = "请在邮箱开通POP3/SMTP!";
 45                 return false;
 46             }
 47             catch (Exception ex)
 48             {
 49                 error = "连接出现异常";
 50                 return false;
 51             }
 52             finally
 53             {
 54                 client.Disconnect();
 55             }
 56             return true;
 57         }
 58         #endregion
 59 
 60 
 61         # region 下载邮件附件
 62         /// <summary>
 63         /// 下载邮件附件
 64         /// </summary>
 65         public void DownAttachments(string path)
 66         {
 67             using (Pop3Client client = new Pop3Client())
 68             {
 69                 if (client.Connected)
 70                 {
 71                     client.Disconnect();
 72                 }
 73                 client.Connect(popServer, popPort, isUseSSL);
 74                 client.Authenticate(accout, pass, AuthenticationMethod.UsernameAndPassword);
 75                 int messageCount = client.GetMessageCount();
 76                 StringBuilder strBuilder = new StringBuilder();
 77                 int count = Convert.ToInt32(SqlHelper.ExecuteScalar("SELECT COUNT(1) FROM EmailList"));
 78                 int i = 1;
 79                 for (i = count + 1; i <= messageCount; i++)
 80                 {
 81                     Message message = client.GetMessage(i);
 82                     string senders = message.Headers.From.DisplayName;
 83                     string from = message.Headers.From.Address;
 84                     string subject = message.Headers.Subject;
 85                     DateTime Datesent = message.Headers.DateSent;
 86 
 87 
 88                     List<MessagePart> messageParts = message.FindAllAttachments();
 89                     foreach (var item in messageParts)
 90                     {
 91                         if (item.IsAttachment)
 92                         {
 93                             if (!File.Exists(path + item.FileName))
 94                             {
 95                                 if (item.FileName.Contains(".zip") || item.FileName.Contains(".rar"))
 96                                     File.WriteAllBytes(path + item.FileName, item.Body);
 97                             }
 98                         }
 99                     }
100 
101                     strBuilder.Append("INSERT INTO [dbo].[EmailList]([Title],[FromAdd],[Time],[isFlag]) VALUES (");
102                     strBuilder.Append("'" + subject + "'," + "'" + from + "'," + "'" + Datesent.ToString("yyyy-MM-dd HH:mm:ss") + "'," + 1);
103                     strBuilder.Append(")");
104                     SqlHelper.ExecuteNonQuery(strBuilder.ToString());
105                     strBuilder.Clear();
106 
107                 }
108             }
109         }
110         #endregion
111 
112 
113         #region 下载邮件附件
114         /// <summary>
115         /// 下载邮件附件
116         /// </summary>
117         public void DownAttachmentsById(string path, int messageId)
118         {
119             using (Pop3Client client = new Pop3Client())
120             {
121                 if (client.Connected)
122                 {
123                     client.Disconnect();
124                 }
125                 client.Connect(popServer, popPort, isUseSSL);
126                 client.Authenticate(accout, pass, AuthenticationMethod.UsernameAndPassword);
127                 Message message = client.GetMessage(messageId);
128                 string senders = message.Headers.From.DisplayName;
129                 string from = message.Headers.From.Address;
130                 string subject = message.Headers.Subject;
131                 DateTime Datesent = message.Headers.DateSent;
132 
133 
134                 List<MessagePart> messageParts = message.FindAllAttachments();
135                 foreach (var item in messageParts)
136                 {
137                     if (item.IsAttachment)
138                     {
139                         if (!File.Exists(path + item.FileName))
140                         {
141                             if (item.FileName.Contains(".zip") || item.FileName.Contains(".rar"))
142                                 File.WriteAllBytes(path + item.FileName, item.Body);
143                         }
144                     }
145                 }
146 
147                 MessagePart nomessageParts = message.FindFirstHtmlVersion();
148                 string html = nomessageParts.GetBodyAsText();
149                 Regex reg = new Regex(@"(?is)<a[^>]*?href=(['""]?)(?<url>[^'""\s>]+)\1[^>]*>(?<text>(?:(?!</?a\b).)*)</a>");
150                 MatchCollection mc = reg.Matches(html);
151                 string url = string.Empty;
152 
153                 url = mc[0].Groups["url"].Value;
154                 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
155                 req.Method = "GET";
156                 using (WebResponse res = req.GetResponse())
157                 {
158                     string reader = new StreamReader(res.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
159                     MatchCollection ms = reg.Matches(reader);
160                     url = ms[0].Groups["url"].Value;
161                 }
162             }
163         }
164         #endregion
165 
166         #region
167         /// <summary>
168         /// 获取邮件数量
169         /// </summary>
170         /// <returns></returns>
171         public int GetEmailCount()
172         {
173             int messageCount = 0;
174             using (Pop3Client client = new Pop3Client())
175             {
176                 if (client.Connected)
177                 {
178                     client.Disconnect();
179                 }
180                 client.Connect(popServer, popPort, isUseSSL);
181                 client.Authenticate(accout, pass, AuthenticationMethod.UsernameAndPassword);
182                 messageCount = client.GetMessageCount();
183             }
184 
185             return messageCount;
186         }
187         #endregion
188 
189 
190     }

猜你喜欢

转载自www.cnblogs.com/ZJ199012/p/9070413.html
今日推荐