C#中用SmtpClient发邮件很简单,闲着无事,简单封装一下

IEmailFactory

public interface IEmailFactory
{
IEmailFactory SetHost(string host);
IEmailFactory SetPort(int port);
IEmailFactory SetUserName(string userName);
IEmailFactory SetPassword(string password);
IEmailFactory SetSSL(bool enableSsl);
IEmailFactory SetTimeout(int timeout);
IEmailFactory SetFromAddress(string address);
IEmailFactory SetFromDisplayName(string displayName);
IEmailFactory LoadFromConfigFile(); //从Config文件中加载配置
IEmailFactory SetSubject(string subject);
IEmailFactory SetBody(string body);
/// <summary>
/// 添加收件人地址(执行多次即添加多个地址)
/// </summary>
IEmailFactory SetToAddress(params string[] addresses);
/// <summary>
/// 添加抄送人地址(执行多次即添加多个地址)
/// </summary>
IEmailFactory SetCcAddress(params string[] addresses);
/// <summary>
/// 添加附件(执行多次即添加多个附件)
/// </summary>
IEmailFactory SetAttachment(params Attachment[] attachments); void Send();
Task SendAsync();
}

EmailFactory

class EmailFactory : IEmailFactory
{
#region properties
protected string Host { get; set; }
protected int Port { get; set; }
protected string UserName { get; set; }
protected string Password { get; set; }
protected bool EnableSSL { get; set; }
protected int? Timeout { get; set; }
protected string FromAddress { get; set; }
protected string FromDisplayName { get; set; }
protected string Subject { get; set; }
protected string Body { get; set; }
protected IList<string> ToList { get; set; }
protected IList<string> CcList { get; set; }
protected IList<Attachment> Attachments { get; set; }
#endregion #region initial methods
public IEmailFactory SetHost(string host)
{
this.Host = host;
return this;
}
public IEmailFactory SetPort(int port)
{
this.Port = port;
return this;
}
public IEmailFactory SetSSL(bool enableSsl)
{
this.EnableSSL = enableSsl;
return this;
}
public IEmailFactory SetTimeout(int timeout)
{
this.Timeout = timeout;
return this;
}
public IEmailFactory SetUserName(string userName)
{
this.UserName = userName;
return this;
}
public IEmailFactory SetPassword(string password)
{
this.Password = password;
return this;
}
public IEmailFactory SetFromAddress(string address)
{
this.FromAddress = address;
return this;
}
public IEmailFactory SetFromDisplayName(string displayName)
{
this.FromDisplayName = displayName;
return this;
}
public IEmailFactory LoadFromConfigFile()
{
var section = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as System.Net.Configuration.SmtpSection;
this.Host = section.Network.Host;
this.Port = section.Network.Port;
this.EnableSSL = section.Network.EnableSsl;
this.UserName = section.Network.UserName;
this.Password = section.Network.Password;
this.FromAddress = section.From;
return this;
}
public IEmailFactory SetSubject(string subject)
{
this.Subject = subject;
return this;
}
public IEmailFactory SetBody(string body)
{
this.Body = body;
return this;
}
public IEmailFactory SetToAddress(params string[] addresses)
{
if (this.ToList == null) this.ToList = new List<string>();
if (addresses != null)
foreach (var item in addresses)
this.ToList.Add(item); return this;
}
public IEmailFactory SetCcAddress(params string[] addresses)
{
if (this.CcList == null) this.CcList = new List<string>();
if (addresses != null)
foreach (var item in addresses)
this.CcList.Add(item); return this;
}
public IEmailFactory SetAttachment(params Attachment[] attachments)
{
if (this.Attachments == null) this.Attachments = new List<Attachment>();
if (attachments != null)
foreach (var item in attachments)
this.Attachments.Add(item); return this;
}
#endregion public virtual void Send()
{
using (SmtpClient smtp = new SmtpClient(this.Host, this.Port))
{
var message = PreSend(smtp);
smtp.Send(message);
}
}
public virtual async Task SendAsync()
{
using (SmtpClient smtp = new SmtpClient(this.Host, this.Port))
{
var message = PreSend(smtp);
await smtp.SendMailAsync(message);
}
} private MailMessage PreSend(SmtpClient smtp)
{
if (this.UserName != null && this.Password != null)
{
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential(this.UserName, this.Password);
}
if (this.Timeout == null)
smtp.Timeout = ; var message = new MailMessage();
message.From = new MailAddress(this.FromAddress, this.FromDisplayName, Encoding.UTF8); if (this.ToList != null)
foreach (var address in this.ToList)
message.To.Add(address); if (this.CcList != null)
foreach (var address in this.CcList)
message.CC.Add(address); if (this.Attachments != null)
foreach (var attachment in this.Attachments)
message.Attachments.Add(attachment); message.Subject = this.Subject;
message.SubjectEncoding = Encoding.UTF8;
message.Body = this.Body;
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
return message;
}
}

EmailWrapper

public class EmailWrapper
{
private static readonly EmailHelper _instance = new EmailHelper();
private EmailHelper() { } public static IEmailFactory Initalize
{
get { return _instance.GetFactory(); }
}
private IEmailFactory GetFactory()
{
return new EmailFactory();
}
}

使用方法:

//同步发送
EmailWrapper.Initalize
.SetHost("smtp.xxxxx.com")
.SetPort()
.SetUserName("xxx@xxxxx.com")
.SetPassword("******")
.SetSSL(false)
.SetFromAddress("xxx@xxxxx.com")
.SetFromDisplayName("Felix")
.SetToAddress("f5.zhang@qq.com", "f5.lee@gmail.com")
.SetCcAddress("f5.chow@yahoo.com")
.SetSubject("会员注册成功")
.SetBody("恭喜你成为会员,为了你的账号安全,请尽快前往安全中心修改登录密码。")
.Send(); //异步发送 从CONFIG中加载配置
await EmailWrapper.Initalize
.LoadFromConfigFile()
.SetFromDisplayName("Felix")
.SetToAddress("f5.zhang@qq.com")
.SetToAddress("f5.lee@gmail.com")
.SetToAddress("f5.chow@yahoo.com")
.SetSubject("会员注册成功")
.SetBody("恭喜你成为会员,为了你的账号安全,请尽快前往安全中心修改登录密码。")
.SendAsync();

分享一个Fluent风格的邮件发送封装类的更多相关文章

  1. Chilkat----开源站点之VS2010 CKMailMan一个很好的邮件发送开源开发包

    Chilkat 是一个很好的开源站点,有各种开源库. 开发语言主要有Classic ASP •C • C++ • C# • Delphi ActiveX • Delphi DLL • Visual F ...

  2. Spring Boot 邮件发送的 5 种姿势!

    邮件发送其实是一个非常常见的需求,用户注册,找回密码等地方,都会用到,使用 JavaSE 代码发送邮件,步骤还是挺繁琐的,Spring Boot 中对于邮件发送,提供了相关的自动化配置类,使得邮件发送 ...

  3. 测试开发【提测平台】分享11-Python实现邮件发送的两种方法实践

    微信搜索[大奇测试开],关注这个坚持分享测试开发干货的家伙. 按照开发安排,本篇本应该是关于提测页面的搜索和显示实现,怕相似内容疲劳,这期改下内容顺序,将邮件服务的相关的提前,在之前的产品需求和原型中 ...

  4. c# 邮件发送代码分享

    /// <summary> /// 发送邮件方法 /// </summary> /// <param name="sendMail">发送人&l ...

  5. VB.NET的一个邮件发送函数

    ''' <summary> ''' VB.NET邮件发送程序 ''' 还没用在别的服务器,不晓得能不能行,慎用! ''' </summary> ''' <param na ...

  6. 补习系列(12)-springboot 与邮件发送【华为云技术分享】

    目录 一.邮件协议 关于数据传输 二.SpringBoot 与邮件 A. 添加依赖 B. 配置文件 C. 发送文本邮件 D.发送附件 E. 发送Html邮件 三.CID与图片 参考文档 一.邮件协议 ...

  7. 分享一个php邮件库——swiftmailer

    最近看到一个好的php邮件库,与phpmailer作用一样,但性能比phpmailer好,尤其是在处理附件的能力上,发送邮件成功的几率也高. github地址:https://github.com/s ...

  8. .NET开发邮件发送功能的全面教程(含邮件组件源码)

    今天,给大家分享的是如何在.NET平台中开发“邮件发送”功能.在网上搜的到的各种资料一般都介绍的比较简单,那今天我想比较细的整理介绍下: 1)         邮件基础理论知识 2)         ...

  9. 使用phantomjs实现highcharts等报表通过邮件发送

    使用phantomjs实现highcharts等报表通过邮件发送(本文仅提供完整解决方案和实现思路,完全照搬不去整理代码无法马上得到效果)   前不久项目组需要将测试相关的质量数据通过每日自动生成报表 ...

随机推荐

  1. 使用PreparedStatement执行SQL语句时占位符(?)的用法

    1.Student数据库表 ID  name gender       2.Java代码 public static void main(String[] args) { int _id=1; Str ...

  2. CentOS7.2设置zabbix

    准备工作 1.lnmp或lamp环境,本机环境:CentOS 7.2 64位,nginx1.10.2 php5.6.26 mysql5.7.15 2.软件Zabbix wget http://nchc ...

  3. 利用javascript、php和ajax实现计算器

    计算器和ajax部分: <?php /** * Created by PhpStorm. * User: Administrator * Date: 16-9-2 * Time: 上午9:20 ...

  4. Android应用与系统安全防御

    来源:HTTP://WWW.CNBLOGS.COM/GOODHACKER/P/3864680.HTML ANDROID应用安全防御 Android应用的安全隐患包括三个方面:代码安全.数据安全和组件安 ...

  5. 使用SWFUpload无刷新上传图片

    使用SWFUpload组件无刷新上传图片 在做项目时,需要用到一个图片的无刷新上传,之前听说过SWFUpload,于是想要通过SWFUpload来进行图片的无刷新上传,由于我的项目属于是ASP.NET ...

  6. oracle10g 统计信息查看、收集

      1. 统计信息查看 1.1 单个表的全局统计信息.统计效果查看 2. 统计信息分析(收集) 2.1 分析工具选择 2.2 分析前做index重建 2.3 分析某数据表,可以在PL/SQL的comm ...

  7. NodeJS: 处理request网页乱码问题

    对于gb2312编码的网页,直接用request去获取会得到乱码的结果,解决方法很简单: 1. npm install iconv-lite 2. var iconv = require('iconv ...

  8. UITabBarController 微信

    AppDelegate.m #import "AppDelegate.h" #import "FirstViewController.h" #import &q ...

  9. MyBatis入门(三)---多个参数

    一.建立表 1.1.建立表,并插入数据 /* SQLyog Enterprise v12.09 (64 bit) MySQL - 5.6.27-log : Database - mybatis *** ...

  10. iOS 7中实现模糊效果

    本文译自iOS 7 Blur Effects with GPUImage. iOS 7在视觉方面有许多改变,其中非常吸引人的功能之一就是在整个系统中巧妙的使用了模糊效果.许多第三方应用程序已经采用了这 ...