使用Net Mail发送邮件
最近用到了发送邮件这个功能,简单记录一下案例。代码如下:
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发送邮件的更多相关文章
- java mail(发送邮件--163邮箱)
package com.util.mail; /** * 发送邮件需要使用的基本信息 */ import java.util.Properties; public class MailSenderIn ...
- Spring Boot 揭秘与实战(七) 实用技术篇 - Java Mail 发送邮件
文章目录 1. Spring Boot 集成 Java Mail 2. 单元测试 3. 源代码 Spring 对 Java Mail 有很好的支持.因此,Spring Boot 也提供了自动配置的支持 ...
- 利用System.Net.Mail 发送邮件
我这里只是试了一下发mail的功能,感觉.net自带的发mail是比较全的,还是直接上我的code 参数文章:System.Net.Mail 发送邮件 SMTP协议 using System; usi ...
- Android Java Mail与Apache Mail发送邮件对比
原文链接: 一.邮件简介 一封邮件由很多信息构成,主要的信息如下,其他的暂时不考虑,例如抄送等: 1.收件人:收件人的邮箱地址,例如xxx@xx.com 2.收件人姓名:大部分的邮件显示时都会显 ...
- linux下使用自带mail发送邮件
linux下使用自带mail发送邮件 mailx工具说明: linux可以通过安装mailx工具,mailx是一个小型的邮件发送程序,一般可以通过该程序在linux系统上,进行监控linux系统状态并 ...
- .net System.Web.Mail发送邮件 (设置发件人 只显示用户名)
http://blog.163.com/hao_2468/blog/static/130881568201141251642215/ .net System.Web.Mail发送邮件 2011-05- ...
- SpringBoot整合Mail发送邮件&发送模板邮件
整合mail发送邮件,其实就是通过代码来操作发送邮件的步骤,编辑收件人.邮件内容.邮件附件等等.通过邮件可以拓展出短信验证码.消息通知等业务. 一.pom文件引入依赖 <dependency&g ...
- 使用Javax.mail 发送邮件
使用Javax.mail 发送邮件 详细说明都在代码中: 引入依赖 <!--sun定义的一套接收.发送电子邮件的API--> <dependency> < ...
- javax.mail 发送邮件异常
一.运行过程抛出异常 1.Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/ ...
- java mail发送邮件
最近做了自动发送邮件功能,带附件的:需要的jar包有
随机推荐
- 队列解密QQ号
队列解密QQ号 本篇博客主要是<啊哈!算法>的读书笔记,这里做一下记录. 问题场景: 给定一串 QQ 号,631758924,从其中解密出真实的 QQ 号. 解密规则:首先将第一个数删除, ...
- Jmeter参数化、检查点、集合点教程
在使用Jemeter做压力测试的时候,往往需要参数化用户名,密码以到达到多用户使用不同的用户名密码登录的目的,这个时候我们就可以使用参数化登录. 一.badboy录制需要的脚本.也可以用fiddler ...
- Scrum冲刺第一篇
一.各个成员在 Alpha 阶段认领的任务 负责人和协作者 任务内容 陈嘉欣 设计编码规范 邓镇港 UI设计 肖烈涛 数据库设计 林德泽 设计测试计划 余晓东 用户注册登陆验证模块 陈嘉欣 余晓东 林 ...
- centos7,python2和python3共存
安装依赖包 yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk- ...
- centos7 下 通过终端 连接 蓝牙设备
#首先确定硬件上有支持蓝牙的设备,插入蓝牙发射器.然后运行如下命令,就可以开到我们的蓝牙设备了: lsusb [root@localhost ~]# lsusbBus 002 Device 003: ...
- LINUX内核CPU负载均衡机制【转】
转自:http://oenhan.com/cpu-load-balance 还是神奇的进程调度问题引发的,参看Linux进程组调度机制分析,组调度机制是看清楚了,发现在重启过程中,很多内核调用栈阻塞在 ...
- 201871010132-张潇潇-《面向对象程序设计(java)》第七周总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- Eclipse的server选项卡中找不到tomcat配置项
1.在Eclipse中,如果想开发j2ee,必须要先安装插件.至于具体的插件安装方法,这里不再赘述. 2.当进行到配置tomcat服务器的时候,有时候会出现这种情况: 3.在server选项卡的Run ...
- Git 克隆远程仓库到本地
Git 克隆远程仓库到本地 参考 $ git clone --help https://git-scm.com/book/zh/v2/Git-%E5%9F%BA%E7%A1%80-%E8%8E%B7% ...
- 八种排序算法原理及Java实现
原文链接:http://ju.outofmemory.cn/entry/372908