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

   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. OC-bug: Undefined symbols for architecture i386: "_OBJC_CLASS_$_JPUSHRegisterEntity", referenced from:

    bug的提示: Undefined symbols for architecture i386: "_OBJC_CLASS_$_JPUSHRegisterEntity", refe ...

  2. Django框架 --序列化组件(serializer)

    一 .Django自带序列化组件 Django内置的serializers(把对象序列化成json字符串) from django.core import serializers from djang ...

  3. Odoo学习笔记一:odoo初探

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/11189194.html 一:Odoo架构 1:数据库服务器层:postgreSQL数据库服务器,用于存储所有 ...

  4. Linux驱动开发常用调试工具---之内存读写工具devmem和devkmem【转】

    转自:https://blog.csdn.net/gatieme/article/details/50964903 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原 ...

  5. python中property简单使用与实现

    property简单使用 class P: """ property简单使用 """ def __init__(self,name): se ...

  6. 2.2 Scala基础知识

    一.基本数据类型和变量 1.基本数据类型 java中每一个数据类型都是一个类: scala没有自己定义String类型,String类型是从java.lang.String照搬的. 字面量(liter ...

  7. linux (08) nginx入门详解

    一. nginx 入门 nginx 入门学习 web服务器软件 windows IIS服务器 linux nginx apache 收费​lighthttp 公司的技术栈 收费版技术栈 apache ...

  8. 快速安装Rainbond——开源企业级Paas平台

    快速安装Rainbond--开源企业级Paas平台 参考:https://www.rainbond.com/docs/user-operations/install/online_install/ R ...

  9. html基础内容

    HTML基础 1. HTML 标题 HTML 标题(Heading)是通过 <h1> - <h6> 等标签进行定义的. 2. HTML 段落 HTML 段落是通过 <p& ...

  10. Maven的Scope区别笔记

    依赖的Scopescope定义了类包在项目的使用阶段.项目阶段包括: 编译,运行,测试和发布. 分类说明compile 默认scope为compile,表示为当前依赖参与项目的编译.测试和运行阶段,属 ...