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

   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());
}
}
}
}

使用Net Mail发送邮件的更多相关文章

  1. java mail(发送邮件--163邮箱)

    package com.util.mail; /** * 发送邮件需要使用的基本信息 */ import java.util.Properties; public class MailSenderIn ...

  2. Spring Boot 揭秘与实战(七) 实用技术篇 - Java Mail 发送邮件

    文章目录 1. Spring Boot 集成 Java Mail 2. 单元测试 3. 源代码 Spring 对 Java Mail 有很好的支持.因此,Spring Boot 也提供了自动配置的支持 ...

  3. 利用System.Net.Mail 发送邮件

    我这里只是试了一下发mail的功能,感觉.net自带的发mail是比较全的,还是直接上我的code 参数文章:System.Net.Mail 发送邮件 SMTP协议 using System; usi ...

  4. Android Java Mail与Apache Mail发送邮件对比

    原文链接: 一.邮件简介  一封邮件由很多信息构成,主要的信息如下,其他的暂时不考虑,例如抄送等:  1.收件人:收件人的邮箱地址,例如xxx@xx.com  2.收件人姓名:大部分的邮件显示时都会显 ...

  5. linux下使用自带mail发送邮件

    linux下使用自带mail发送邮件 mailx工具说明: linux可以通过安装mailx工具,mailx是一个小型的邮件发送程序,一般可以通过该程序在linux系统上,进行监控linux系统状态并 ...

  6. .net System.Web.Mail发送邮件 (设置发件人 只显示用户名)

    http://blog.163.com/hao_2468/blog/static/130881568201141251642215/ .net System.Web.Mail发送邮件 2011-05- ...

  7. SpringBoot整合Mail发送邮件&发送模板邮件

    整合mail发送邮件,其实就是通过代码来操作发送邮件的步骤,编辑收件人.邮件内容.邮件附件等等.通过邮件可以拓展出短信验证码.消息通知等业务. 一.pom文件引入依赖 <dependency&g ...

  8. 使用Javax.mail 发送邮件

    使用Javax.mail 发送邮件 详细说明都在代码中: 引入依赖  <!--sun定义的一套接收.发送电子邮件的API-->    <dependency>      < ...

  9. javax.mail 发送邮件异常

    一.运行过程抛出异常 1.Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/ ...

  10. java mail发送邮件

    最近做了自动发送邮件功能,带附件的:需要的jar包有

随机推荐

  1. 【AI测试】也许这有你想知道的人工智能 (AI) 测试--开篇

    人工智能测试 什么是人工智能,人工智能是怎么测试的.可能是大家一开始最想了解的. 大家看图中关于人工智能的定义.通俗点来说呢,就是 让机器实现原来只有人类才能完成的任务:比如看懂照片,听懂说话,思考等 ...

  2. visudo: /etc/sudoers is busy, try again later

    启动visudo时,报错"visudo: /etc/sudoers is busy, try again later" 解决思路:杀掉visudo进程 ps -ef|grep vi ...

  3. MVC的View本质和扩展

    一:网站启动流程简介 前面两节我们有介绍管道处理模型,然后下图总结出了mvc启动的整个流程 二:MVC返回的三种结果 从之前的流程已经反编译源码我们晓的,mvc最终都会返回一个结果,其中大概分为以下三 ...

  4. 3.2 Spark运行架构

    一.基本概念 1.RDD Resillient Distributed Dataset 弹性分布式数据集 2.DAG 反映RDD之间的依赖关系 3.Executor 进程驻守在机器上面,由进程派生出很 ...

  5. Linux环境下sudo切换用户后执行其他命令

    https://blog.csdn.net/liangxw1/article/details/80106465

  6. python27期day04:列表、元组、range、作业题。

    1.for循环套for循环: for i in "abc": for x in "egf: print(x) 结果是:e g f e g f e g f  2.99乘法表 ...

  7. springboot+springmvc拦截器做登录拦截

    springboot+springmvc拦截器做登录拦截 LoginInterceptor 实现 HandlerInterceptor 接口,自定义拦截器处理方法 LoginConfiguration ...

  8. Jmeter接口测试,怎么在下一个接口调用上一个接口的数据

    常用的两种方式,第二种容易上手1.使用正则提取器 jmeter 如何将上一个请求的结果作为下一个请求的参数——使用正则提取器(http://www.cnblogs.com/0201zcr/p/5089 ...

  9. javascript中的e是什么意思?

    e 代表事件(event)对象,即所谓的事件驱动源,包含了许多属性和方法.下面以鼠标点击事件为例,作一个测试: (HTML) <!DOCTYPE html> <html> &l ...

  10. Python程序设计例题

    例一:蒙特卡罗方法求解 π 值 from random import random from math import sqrt from time import clock DARTS=1000 hi ...