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

   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. Jsp调用淘宝IP地址库获取来访IP详细信息

    Jsp调用淘宝IP地址库获取来访IP详细信息   示例网页点击:www.trembler.cn/ipinfo/ipinfo(服务器有其他用处,页面已失效) String ip = request.ge ...

  2. Spring获取springmvc的controller bean

    有个特殊需求,一个普通的类,定时任务,需要获取SpringMVC的controller对应的bean: 方法: WebApplicationContext wac = ContextLoader.ge ...

  3. PHP扩展使用-CURL

    一.简介 功能:是一个可以使用URL的语法模拟浏览器来传输数据的工具库,支持的协议http.https.ftp.gopher.telnet.dict.file.ldap 资源类型:cURL 句柄和 c ...

  4. 关于Apache本地能访问外网不能访问的问题

    title: 关于Apache本地能访问外网不能访问的问题 date: 2018-08-05 19:22:12 tags: web --- 在配置apache和tomcat时,把它们都配置好,放到服务 ...

  5. 第18.2节_地址类型与LL层设备过滤

    一.地址类型 二.白名单和Resolving List 三.LL层设备过滤 一.地址类型 学习资料:官方手册 Vol 6: Core System Package [Low Energy Contro ...

  6. 201871010131-张兴盼《面向对象程序设计(java)》第十四周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业要求在哪里 https://www.cnblogs.com/lily-2018/p/1 ...

  7. LG1983 「NOIP2013」车站分级 拓扑排序

    问题描述 LG1983 题解 考虑建立有向边\((a,b)\),代表\(a\)比\(b\)低级. 于是枚举每一辆车次经过的车站\(x \in [l,r]\),如果不是车辆停靠的车站,则从\(x\)向每 ...

  8. Educational Codeforces Round 57 (Rated for Div. 2) D dp

    https://codeforces.com/contest/1096/problem/D 题意 给一个串s,删掉一个字符的代价为a[i],问使得s的子串不含"hard"的最小代价 ...

  9. 喜欢去知乎炸鱼?用python吧

    知乎高赞贴: 有一双大长腿是什么体验? 有一副迷人的身材是什么体验? 别用手机费劲的翻了,python帮你一臂之力 import re import requests import os import ...

  10. [转载]3.11 UiPath存在文本Text Exists的介绍和使用

    一.Text Exists的介绍 检查是否在给定的UI元素中找到了文本,输出的是一个布尔值 二.Text Exists在UiPath中的使用 1.打开设计器,在设计库中新建一个Sequence,为序列 ...