使用Net Mail发送邮件

 

最近用到了发送邮件这个功能,简单记录一下案例。代码如下:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Configuration;
  6 using System.Net.Mail;
  7 using HtmlAgilityPack;
  8 using System.IO;
  9 using System.Transactions;
 10 using System.Text.RegularExpressions;
 11 using NLog;
 12 using System.Web;
 13 using System.Data;
 15 using System.Net;
 16 using System.Net.Mime;
 17 
 18 namespace Services
 19 {
 20     public class SendEmailService
 21     {
 22         public static string FROM => ConfigurationManager.AppSettings["SenderEmailAddress"];
 23         public static string FROM_DISPLAY_NAME => ConfigurationManager.AppSettings["SenderName"];
 24         public static String USERNAME => ConfigurationManager.AppSettings["SenderUserName"];
 25         public static String PASSWORD => ConfigurationManager.AppSettings["SenderPwd"];
 26         public static String HOST => ConfigurationManager.AppSettings["Host"];
 27         public static int PORT => int.Parse(ConfigurationManager.AppSettings["ServerPort"]);
 28         public static int TIMEOUT => int.Parse(ConfigurationManager.AppSettings["TimeOut"]);
 29         public static Boolean ENABLESSL => Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"]);
 30         public static String SUBACCOUNT => ConfigurationManager.AppSettings["SubAccount"];
 31 
 32         private static Logger logger = LogManager.GetCurrentClassLogger();
 33 
 34         public const string EmptyString = "";
 35 
 36         public static string Send(List<string> toList, List<string> ccList, List<string> bccList, string subject, string body, List<string> attachments, Stream stream = null, string fileName = "")
 37         {
 38 
 39             string msg = string.Empty;
 40             int emailTriggerStatus = int.Parse(ConfigurationManager.AppSettings["Email_TriggerStatus"]);
 41             List<string> validEmailList = new List<string>();
 42             List<string> validEmailCcList = new List<string>();
 43             List<string> validEmailBccList = new List<string>();
 44             try
 45             {
 46                 MailMessage mailMsg = new MailMessage();
 47                 IEnumerable<string> finalToRecipients = null;
 48                 IEnumerable<string> finalCcRecipients = null;
 49                 IEnumerable<string> finalBccRecipients = null;
 50                 if (emailTriggerStatus == Globals.EMAIL_NOT_SEND)
 51                 {
 52                     logger.Info(Globals.EMAIL_LOGGER);
 53                 }
 54                 else
 55                 {
 56                     foreach (string email in toList)
 57                     {
 58                         if (UtilityService.IsValidEmail(email))
 59                         {
 60                             validEmailList.Add(email);
 61                         }
 62                     }
 63 
 64                     finalToRecipients = validEmailList.Distinct();
 65                     if (!ccList.IsNullOrEmpty())
 66                     {
 67                         foreach (string email in ccList)
 68                         {
 69                             if (UtilityService.IsValidEmail(email))
 70                             {
 71                                 validEmailCcList.Add(email);
 72                             }
 73                         }
 74                     }
 75 
 76                     // both Emailto and EmailCC null , not send email
 77                     if (!(validEmailList.IsNullOrEmpty()))
 78                     {
 79                         if (!validEmailCcList.IsNullOrEmpty())
 80                         {
 81                             finalCcRecipients = validEmailCcList.Where(m => !finalToRecipients.Contains(m)).Distinct();
 82                         }
 83 
 84                         if (!bccList.IsNullOrEmpty())
 85                         {
 86                             foreach (string email in bccList)
 87                             {
 88                                 if (UtilityService.IsValidEmail(email))
 89                                 {
 90                                     validEmailBccList.Add(email);
 91                                 }
 92                             }
 93                         }
 94 
 95                         if (!validEmailBccList.IsNullOrEmpty())
 96                         {
 97                             finalBccRecipients = validEmailBccList.Where(m => !finalToRecipients.Contains(m)).Distinct();
 98                         }
 99 
100                         foreach (string to in finalToRecipients)
101                         {
102                             mailMsg.To.Add(to);
103                         }
104                         if (!finalCcRecipients.IsNullOrEmpty())
105                         {
106                             foreach (string cc in finalCcRecipients)
107                             {
108                                 mailMsg.CC.Add(cc);
109                             }
110                         }
111 
112                         //BCC
113                         if (!finalBccRecipients.IsNullOrEmpty())
114                         {
115                             foreach (string bcc in finalBccRecipients)
116                             {
117                                 mailMsg.Bcc.Add(bcc);
118                             }
119                         }
120 
121                         //attachments
122                         if (!attachments.IsNullOrEmpty())
123                         {
124                             foreach (string attachment in attachments)
125                             {
126                                 Attachment attachmentFile = new Attachment(attachment); //create the attachment
127                                 mailMsg.Attachments.Add(attachmentFile);
128                             }
129                         }
130 
131                         if (!stream.IsNull() && fileName.ToLower().IndexOf(".pdf") > 0)
132                         {
133                             ContentType ct = new ContentType(MediaTypeNames.Application.Pdf);
134                             Attachment attachmentFile = new Attachment(stream, ct); //create the attachment
135                             mailMsg.Attachments.Add(attachmentFile);
136                             attachmentFile.ContentDisposition.FileName = fileName;
137                         }
138                         if (!stream.IsNull() && fileName.ToLower().IndexOf(".xlsx") > 0)
139                         {
140                             Attachment attachmentFile = new Attachment(stream, fileName); //create the attachment
141                             mailMsg.Attachments.Add(attachmentFile);
142                             attachmentFile.ContentDisposition.FileName = fileName;
143                         }
144 
145                         mailMsg.IsBodyHtml = true;
146                         // From
147                         MailAddress mailAddress = new MailAddress(FROM, FROM_DISPLAY_NAME);
148                         mailMsg.From = mailAddress;
149 
150                         // Subject and Body
151                         if (emailTriggerStatus == Globals.EMAIL_SEND_PRIMARY_EMAIL_TESTING)
152                         {
153                             subject = "[RTS TEST IGNORE]: " + subject;
154                         }
155 
156                         if (!SUBACCOUNT.IsNullOrEmpty())
157                         {
158                             mailMsg.Headers.Add("X-MC-Subaccount", SUBACCOUNT);
159                         }
160 
161                         mailMsg.Subject = subject;
162                         mailMsg.Body = body;
163 
164                         // Init SmtpClient and send
165                         SmtpClient smtpClient = new SmtpClient();
166                         if (!string.IsNullOrEmpty(USERNAME) && !string.IsNullOrEmpty(PASSWORD))
167                         {
168                             NetworkCredential credentials = new NetworkCredential(USERNAME, PASSWORD);
169                             smtpClient.Credentials = credentials;
170                         }
171                         smtpClient.Timeout = Convert.ToInt32(TIMEOUT);
172                         smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
173                         smtpClient.Host = HOST;
174                         smtpClient.Port = Convert.ToInt32(PORT);
175                         smtpClient.EnableSsl = ENABLESSL;
176                         smtpClient.UseDefaultCredentials = true;
177                         smtpClient.Send(mailMsg);
178 
179                         mailMsg.Attachments.Dispose();
180                         mailMsg.Dispose();
183                 }
184             }
185             catch (Exception ex)
186             {
187                 msg = ex.Message;
188                 logger.Error(ex);
189             }
190             finally
191             {
192                 if (!stream.IsNull())
193                     stream.Close();
194             }
195             return msg;
196         }
197 
198         public static string Send(List<string> toList, List<string> ccList, string subject, string body, List<string> attachments)
199         {
200             return Send(toList, ccList, null, subject, body, attachments);
201         }
202 
203         public static void SendApprovalNotifyEmail(string emailTo, List<AlertEmailUserInfo> alertEmailUserInfos,
204                                                    List<string> emailCC = null, List<string> emailBCC = null,
205                                                    List<string> attachment = null, string subject = "",
206                                                    string text = "", SendType sendType = SendType.PreAlert)
207         {
208             try
209             {
210                 SendEmail(emailTo, alertEmailUserInfos, emailCC, emailBCC, attachment, subject, text, sendType);
211             }
212             catch (Exception ex)
213             {
214                 logger.Error(ex.ToString());
215             }
216         }
217 
218         private static void SendEmail(string emailTo, List<AlertEmailUserInfo> alertEmailUserInfos,
219                                       List<string> emailCC = null, List<string> emailBCC = null,
220                                       List<string> attachment = null, string subject = "",
221                                       string perText = "", SendType sendType = SendType.PreAlert)
222         {
223             try
224             {
225                 HtmlDocument html = new HtmlDocument();
226                 string tempPath = ConfigurationManager.AppSettings["TemplatePath"];
227                 html.Load(tempPath);
228                 StringBuilder sb = new StringBuilder();
229                 sb.Append("<table>");
230                 sb.Append("<thead>");
231                 sb.Append("<tr>");
232                 sb.Append("<td>email</td><td>ID</td>");
233                 sb.Append("</tr>");
234                 sb.Append("</thead>");
235                 sb.Append("<tbody>");
236                 foreach (var item in alertEmailUserInfos)
237                 {
238                     sb.Append("<tr>");
239                     sb.AppendFormat("<td>{0}</td>", item.a);
240                     sb.AppendFormat("<td>{0}</td>", item.b);
241                     sb.AppendFormat("<td " + (item.c? "class=\"redText\"" : "") + ">{0}</td>", item.d);
242                    
243                     sb.Append("</tr>");
244                 }
245                 sb.Append("</tbody>");
246                 sb.Append("</table>");
247                 var nodeCollection = html.DocumentNode.SelectNodes("//*[@id=\"tableParent\"]");
248                 foreach (var item in nodeCollection)
249                 {
250                     item.InnerHtml = sb.ToString();
251                 }
252                 using (MemoryStream stream = new MemoryStream())
253                 {
254                     html.Save(stream);
255                     stream.Seek(0, SeekOrigin.Begin);
256                     if (stream != null)
257                     {
258                         using (StreamReader streamGSKU = new StreamReader(stream))
259                         {
260                             string plmail = "";
261                             List<string> emailToList = new List<string>();
262                             emailToList.AddRange(emailTo.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
263                             plmail = Send(emailToList, emailCC, emailBCC, subject, perText + "<br/><br/>" + streamGSKU.ReadToEnd(),
264                                           attachment);
265                         }
266                     }
267                 }
268             }
269             catch (Exception ex)
270             {
271                 logger.Error(ex.ToString());
272             }
273         }
274     }
275 }

 

posted @ 2019-09-04 09:50  祁临芯  阅读(508)  评论(0编辑  收藏  举报
友情链接:初心商城