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

   using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Net.Mail;
using HtmlAgilityPack;
using System.IO;
using System.Transactions;
using System.Text.RegularExpressions;
using NLog;
using System.Web;
using System.Data;
using System.Net;
using System.Net.Mime; namespace Services
{
public class SendEmailService
{
public static string FROM => ConfigurationManager.AppSettings["SenderEmailAddress"];
public static string FROM_DISPLAY_NAME => ConfigurationManager.AppSettings["SenderName"];
public static String USERNAME => ConfigurationManager.AppSettings["SenderUserName"];
public static String PASSWORD => ConfigurationManager.AppSettings["SenderPwd"];
public static String HOST => ConfigurationManager.AppSettings["Host"];
public static int PORT => int.Parse(ConfigurationManager.AppSettings["ServerPort"]);
public static int TIMEOUT => int.Parse(ConfigurationManager.AppSettings["TimeOut"]);
public static Boolean ENABLESSL => Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"]);
public static String SUBACCOUNT => ConfigurationManager.AppSettings["SubAccount"]; private static Logger logger = LogManager.GetCurrentClassLogger(); public const string EmptyString = ""; 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 = "")
{ string msg = string.Empty;
int emailTriggerStatus = int.Parse(ConfigurationManager.AppSettings["Email_TriggerStatus"]);
List<string> validEmailList = new List<string>();
List<string> validEmailCcList = new List<string>();
List<string> validEmailBccList = new List<string>();
try
{
MailMessage mailMsg = new MailMessage();
IEnumerable<string> finalToRecipients = null;
IEnumerable<string> finalCcRecipients = null;
IEnumerable<string> finalBccRecipients = null;
if (emailTriggerStatus == Globals.EMAIL_NOT_SEND)
{
logger.Info(Globals.EMAIL_LOGGER);
}
else
{
foreach (string email in toList)
{
if (UtilityService.IsValidEmail(email))
{
validEmailList.Add(email);
}
} finalToRecipients = validEmailList.Distinct();
if (!ccList.IsNullOrEmpty())
{
foreach (string email in ccList)
{
if (UtilityService.IsValidEmail(email))
{
validEmailCcList.Add(email);
}
}
} // both Emailto and EmailCC null , not send email
if (!(validEmailList.IsNullOrEmpty()))
{
if (!validEmailCcList.IsNullOrEmpty())
{
finalCcRecipients = validEmailCcList.Where(m => !finalToRecipients.Contains(m)).Distinct();
} if (!bccList.IsNullOrEmpty())
{
foreach (string email in bccList)
{
if (UtilityService.IsValidEmail(email))
{
validEmailBccList.Add(email);
}
}
} if (!validEmailBccList.IsNullOrEmpty())
{
finalBccRecipients = validEmailBccList.Where(m => !finalToRecipients.Contains(m)).Distinct();
} foreach (string to in finalToRecipients)
{
mailMsg.To.Add(to);
}
if (!finalCcRecipients.IsNullOrEmpty())
{
foreach (string cc in finalCcRecipients)
{
mailMsg.CC.Add(cc);
}
} //BCC
if (!finalBccRecipients.IsNullOrEmpty())
{
foreach (string bcc in finalBccRecipients)
{
mailMsg.Bcc.Add(bcc);
}
} //attachments
if (!attachments.IsNullOrEmpty())
{
foreach (string attachment in attachments)
{
Attachment attachmentFile = new Attachment(attachment); //create the attachment
mailMsg.Attachments.Add(attachmentFile);
}
} if (!stream.IsNull() && fileName.ToLower().IndexOf(".pdf") > )
{
ContentType ct = new ContentType(MediaTypeNames.Application.Pdf);
Attachment attachmentFile = new Attachment(stream, ct); //create the attachment
mailMsg.Attachments.Add(attachmentFile);
attachmentFile.ContentDisposition.FileName = fileName;
}
if (!stream.IsNull() && fileName.ToLower().IndexOf(".xlsx") > )
{
Attachment attachmentFile = new Attachment(stream, fileName); //create the attachment
mailMsg.Attachments.Add(attachmentFile);
attachmentFile.ContentDisposition.FileName = fileName;
} mailMsg.IsBodyHtml = true;
// From
MailAddress mailAddress = new MailAddress(FROM, FROM_DISPLAY_NAME);
mailMsg.From = mailAddress; // Subject and Body
if (emailTriggerStatus == Globals.EMAIL_SEND_PRIMARY_EMAIL_TESTING)
{
subject = "[RTS TEST IGNORE]: " + subject;
} if (!SUBACCOUNT.IsNullOrEmpty())
{
mailMsg.Headers.Add("X-MC-Subaccount", SUBACCOUNT);
} mailMsg.Subject = subject;
mailMsg.Body = body; // Init SmtpClient and send
SmtpClient smtpClient = new SmtpClient();
if (!string.IsNullOrEmpty(USERNAME) && !string.IsNullOrEmpty(PASSWORD))
{
NetworkCredential credentials = new NetworkCredential(USERNAME, PASSWORD);
smtpClient.Credentials = credentials;
}
smtpClient.Timeout = Convert.ToInt32(TIMEOUT);
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Host = HOST;
smtpClient.Port = Convert.ToInt32(PORT);
smtpClient.EnableSsl = ENABLESSL;
smtpClient.UseDefaultCredentials = true;
smtpClient.Send(mailMsg); mailMsg.Attachments.Dispose();
mailMsg.Dispose();
}
}
catch (Exception ex)
{
msg = ex.Message;
logger.Error(ex);
}
finally
{
if (!stream.IsNull())
stream.Close();
}
return msg;
} public static string Send(List<string> toList, List<string> ccList, string subject, string body, List<string> attachments)
{
return Send(toList, ccList, null, subject, body, attachments);
} public static void SendApprovalNotifyEmail(string emailTo, List<AlertEmailUserInfo> alertEmailUserInfos,
List<string> emailCC = null, List<string> emailBCC = null,
List<string> attachment = null, string subject = "",
string text = "", SendType sendType = SendType.PreAlert)
{
try
{
SendEmail(emailTo, alertEmailUserInfos, emailCC, emailBCC, attachment, subject, text, sendType);
}
catch (Exception ex)
{
logger.Error(ex.ToString());
}
} private static void SendEmail(string emailTo, List<AlertEmailUserInfo> alertEmailUserInfos,
List<string> emailCC = null, List<string> emailBCC = null,
List<string> attachment = null, string subject = "",
string perText = "", SendType sendType = SendType.PreAlert)
{
try
{
HtmlDocument html = new HtmlDocument();
string tempPath = ConfigurationManager.AppSettings["TemplatePath"];
html.Load(tempPath);
StringBuilder sb = new StringBuilder();
sb.Append("<table>");
sb.Append("<thead>");
sb.Append("<tr>");
sb.Append("<td>email</td><td>ID</td>");
sb.Append("</tr>");
sb.Append("</thead>");
sb.Append("<tbody>");
foreach (var item in alertEmailUserInfos)
{
sb.Append("<tr>");
sb.AppendFormat("<td>{0}</td>", item.a);
sb.AppendFormat("<td>{0}</td>", item.b);
sb.AppendFormat("<td " + (item.c? "class=\"redText\"" : "") + ">{0}</td>", item.d); sb.Append("</tr>");
}
sb.Append("</tbody>");
sb.Append("</table>");
var nodeCollection = html.DocumentNode.SelectNodes("//*[@id=\"tableParent\"]");
foreach (var item in nodeCollection)
{
item.InnerHtml = sb.ToString();
}
using (MemoryStream stream = new MemoryStream())
{
html.Save(stream);
stream.Seek(, SeekOrigin.Begin);
if (stream != null)
{
using (StreamReader streamGSKU = new StreamReader(stream))
{
string plmail = "";
List<string> emailToList = new List<string>();
emailToList.AddRange(emailTo.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
plmail = Send(emailToList, emailCC, emailBCC, subject, perText + "<br/><br/>" + streamGSKU.ReadToEnd(),
attachment);
}
}
}
}
catch (Exception ex)
{
logger.Error(ex.ToString());
}
}
}
}

最新文章

  1. 压力测试之badboy和Jmeter的简单使用方法
  2. Oracle语句优化之一
  3. 【转】appStore上传苹果应用程序软件发布流程
  4. IOS开发中的几种设计模式
  5. Ubuntu 14.04 忘记用户密码(备忘)
  6. Oracle修改被占用的临时表结构
  7. jsp中利用java代码换行
  8. css3中动画animation的应用
  9. C/C++代码静态检查工具Cppcheck在VS2008开发环境中的安装配置和使用
  10. Spring3.0官网文档学习笔记(七)--3.4.2
  11. C#中的Dictionary的使用
  12. STM32库函数void USART_SendData的缺陷和解决方法
  13. 用不用lambda,这是一个问题
  14. 基于RBAC模型的权限系统设计(Github开源项目)
  15. Spring4之IOC
  16. bootstrap-treeview 中文开发手册
  17. Python &#183; 进度条
  18. ASM X86&&X64 Registers 对寄存器ESP和EBP的一些理解
  19. 【占位符替换】替换String中的占位符标志位{placeholder}
  20. vue2.0路由-适合刚接触新手简单理解

热门文章

  1. flask上下文管理之threading.local
  2. ensorFlow的安装
  3. 201871010106-丁宣元 《面向对象程序设计(java)》第八周学习总结
  4. 201871010125 王玉江 《面向对象程序设计(Java)》第八周实验总结
  5. python在windows系统上创建文件
  6. CentOS 8 正式发布!
  7. LG2512/BZOJ1045 「HAOI2008」糖果传递 中位数
  8. 【oracle】lpad函数 作用(填充)
  9. Zabbix介绍及安装
  10. [NOI2019]回家路线(最短路,斜率优化)