- System.Web.Mail 与 System.Net.Mail 的区别
- 使用 System.Web.Mail 发送邮件
- 使用 System.Net.Mail 发送邮件
System.Web.Mail 和 System.Net.Mail 都可以实现基本邮件发送,但有几个非常重要的区别,使用时需要根据实际情况进行选择。
1.System.Web.Mail 不是SMTP协议的完整.NET本机实现,它使用CDONTS中预先存在的COM功能,发送HTML消息时如果带有嵌入资源(如图像)等需要做一些额外的处理(比如使用文件路径构造附件)。
2.System.Net.Mail 名称空间是 .NET Framework 2.0 版中是新增的,包含用于将电子邮件发送到简单邮件传输协议 (SMTP) 服务器进行传送的类,能够正确支持 MIME,因此可以生成带有嵌入资源(如图像)的格式化HTML消息,实现了SMTP客户端的完整功能,在 System.Net.Mail 上遇到的问题要少得多,因为它避免了因COM导致的问题。
3.System.Web.Mail 命名空间已被微软标记为弃用,使用时可能需要屏蔽弃用警告。
4.System.Net.Mail 不支持 Implicit SSL 方式发送邮件,这可能导致许多邮件发送程序从System.Web.Mail切换到System.Net.Mail后无法正常工作。例如国内很多邮件服务商提供SMTP服务的465端口,使用的是隐式加密协议。
使用 System.Web.Mail 发送邮件以下是一个使用 System.Web.Mail 发送邮件的类,简单实现了异步发送,如果发送的html消息带有附件,需要使用其中的方法添加内联附件 AddAttachmentsInside
using System;
using System.Collections.Generic;
using System.Web.Mail;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace AShenInfrastructure.Email
{
#pragma warning disable 0618
///
/// 邮件客户端 System.Web
/// 一般用于 Implicit SSL 的邮箱服务 465端口
///
public class WebEmailClient
{
#region 私有函数
private readonly System.Web.Mail.MailMessage _mailMessage; //处理发送邮件的内容(如:收发人地址、标题、主体、图片、附件)
private EventHandler m_OnSendCompleted = null;
#endregion
#region 构造函数
///
/// 构造函数
///
/// 发件邮箱
/// 发件邮箱的密码
/// 发件箱的邮件服务器地址
/// 发送邮件所用的端口号(stmp协议默认为25)
/// true表示对邮件内容进行ssl加密传输,false表示不加密
public WebEmailClient(string username, string password, string server, int port, bool sslEnable)
{
_mailMessage = new System.Web.Mail.MailMessage();
_mailMessage.BodyFormat = System.Web.Mail.MailFormat.Text;
_mailMessage.BodyEncoding = Encoding.UTF8;
_mailMessage.Priority = System.Web.Mail.MailPriority.High;//优先级
_mailMessage.Fields.Add("server", server);
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", username);//登陆名
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password);//登陆密码
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", port);//端口
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", sslEnable.ToString().ToLower());
}
///
/// 构造函数
///
/// 发件邮箱
/// 发件邮箱的密码
/// 发件箱的邮件服务器地址
/// 发送邮件所用的端口号(stmp协议默认为25)
/// true表示对邮件内容进行ssl加密传输,false表示不加密
/// 发件人地址
/// 发件人名称
public WebEmailClient(string username, string password, string server, int port, bool sslEnable, string fromAddress, string displayName)
{
_mailMessage = new System.Web.Mail.MailMessage();
_mailMessage.BodyFormat = System.Web.Mail.MailFormat.Text;
_mailMessage.BodyEncoding = Encoding.UTF8;
_mailMessage.Priority = System.Web.Mail.MailPriority.High;//优先级
_mailMessage.From = fromAddress ?? displayName;
_mailMessage.Fields.Add("server", server);
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", username);//登陆名
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password);//登陆密码
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", port);//端口
_mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", sslEnable.ToString().ToLower());
}
#endregion
#region 公共属性
///
/// 邮件发送完成回调事件
///
public event EventHandler SendAsyncCompleted
{
add { m_OnSendCompleted += value; }
remove { m_OnSendCompleted -= value; }
}
///
/// 发件人信息
///
public string From
{
get { return _mailMessage.From; }
set { _mailMessage.From = value; }
}
///
/// 邮件主题
///
public string Subject
{
get { return _mailMessage.Subject; }
set { _mailMessage.Subject = value; }
}
///
/// 邮件内容
///
public string Body
{
get { return _mailMessage.Body; }
set { _mailMessage.Body = value; }
}
///
/// 是否为html内容
///
public bool IsBodyHtml
{
get { return _mailMessage.BodyFormat == System.Web.Mail.MailFormat.Html; }
set { _mailMessage.BodyFormat = value ? System.Web.Mail.MailFormat.Html : System.Web.Mail.MailFormat.Text; }
}
///
/// 邮件优先级:低、正常、紧急,默认为 正常
///
public System.Web.Mail.MailPriority MailPrioty
{
get { return _mailMessage.Priority; }
set { _mailMessage.Priority = value; }
}
///
/// 收件人信息
///
public string To
{
get { return _mailMessage.To; }
}
#endregion
#region 公共函数
///
/// 添加附件
///
///附件的路径集合
public void AddAttachments(IEnumerable paths)
{
foreach (var item in paths)
{
var data = new System.Net.Mail.Attachment(item, System.Net.Mime.MediaTypeNames.Application.Octet);
var disposition = data.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(item);
disposition.ModificationDate = File.GetLastWriteTime(item);
disposition.ReadDate = File.GetLastAccessTime(item);
_mailMessage.Attachments.Add(data);
}
}
///
/// 添加内联附件
/// 不显示在附件里,直接可以用id显示在html内容中,一般用于图片附件
/// 可以用文件id嵌入html
///
///附件的路径集合
public void AddAttachmentsInside(IEnumerable paths)
{
foreach (var item in paths)
{
var data = new System.Net.Mail.Attachment(item, System.Net.Mime.MediaTypeNames.Application.Octet);
var disposition = data.ContentDisposition;
data.ContentDisposition.CreationDate = File.GetCreationTime(item);
data.ContentDisposition.ModificationDate = File.GetLastWriteTime(item);
data.ContentDisposition.ReadDate = File.GetLastAccessTime(item);
data.ContentId = System.IO.Path.GetFileNameWithoutExtension(item);
_mailMessage.Attachments.Add(data);
}
}
///
/// 清除附件
///
public void ClearAttachments()
{
_mailMessage.Attachments.Clear();
}
///
/// 发送邮件(同步方式,发送异常时抛出)
///
/// 收件人
public void Send(string toEmail)
{
_mailMessage.To = toEmail;
System.Web.Mail.SmtpMail.SmtpServer = _mailMessage.Fields["server"].ToString();
System.Web.Mail.SmtpMail.Send(_mailMessage);
}
///
/// 发送邮件(异步方式,发送异常时回调中返回)
///
/// 收件人
///
public Task SendAsync(string toEmail)
{
Task task = Task.Factory.StartNew(() =>
{
_mailMessage.To = toEmail;
System.Web.Mail.SmtpMail.SmtpServer = _mailMessage.Fields["server"].ToString();
System.Web.Mail.SmtpMail.Send(_mailMessage);
});
task.Wait();
task.ContinueWith((e) =>
{
if (m_OnSendCompleted != null)
{
this.m_OnSendCompleted.Invoke(e, new WebAsyncCompletedEventArgs(e.Exception, e.IsCanceled, null));
}
});
return task;
}
#endregion
public class WebAsyncCompletedEventArgs
{
private readonly bool _Cancelled;
private readonly Exception _Error;
private readonly object _UserState;
public WebAsyncCompletedEventArgs() { }
public WebAsyncCompletedEventArgs(Exception error, bool cancelled, object userState)
{
_Error = error;
_Cancelled = cancelled;
_UserState = userState;
}
public bool Cancelled
{
get { return _Cancelled; }
}
public Exception Error
{
get { return _Error; }
}
public object UserState
{
get { return _UserState; }
}
}
}
}
使用 System.Net.Mail 发送邮件
以下是一个使用 System.Net.Mail 发送邮件的类
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
namespace AShenInfrastructure.Email
{
///
/// 邮件客户端 System.Net
/// 非 Implicit SSL 邮箱适用 非465端口
///
public class NetEmailClient
{
#region 私有函数
private readonly System.Net.Mail.MailMessage _mailMessage; //处理发送邮件的内容(如:收发人地址、标题、主体、图片、附件)
private readonly System.Net.Mail.SmtpClient _smtpClient; //处理用smtp方式发送此邮件的配置信息(如:邮件服务器、发送端口号、验证方式)
private EventHandler m_OnSendCompleted = null;
#endregion
#region 构造函数
///
/// 构造函数
///
/// 发件邮箱
/// 发件邮箱的密码
/// 发件箱的邮件服务器地址
/// 发送邮件所用的端口号(stmp协议默认为25)
/// true表示对邮件内容进行ssl加密传输,false表示不加密
public NetEmailClient(string username, string password, string server, int port, bool sslEnable)
{
_smtpClient = new System.Net.Mail.SmtpClient(server, port);
_smtpClient.EnableSsl = sslEnable;
_smtpClient.Credentials = new System.Net.NetworkCredential(username, password);//用户名和密码
_smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;//指定电子邮件发送方式
_smtpClient.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(m_SendCompleted);
_mailMessage = new System.Net.Mail.MailMessage();
_mailMessage.IsBodyHtml = false;
_mailMessage.BodyEncoding = Encoding.UTF8;
_mailMessage.Priority = System.Net.Mail.MailPriority.High;//优先级
}
///
/// 构造函数
///
/// 发件邮箱
/// 发件邮箱的密码
/// 发件箱的邮件服务器地址
/// 发送邮件所用的端口号(stmp协议默认为25)
/// true表示对邮件内容进行ssl加密传输,false表示不加密
/// 发件人邮箱地址
/// 发件人显示名称
public NetEmailClient(string username, string password, string server, int port, bool sslEnable, string fromAddress, string displayName)
{
_smtpClient = new System.Net.Mail.SmtpClient(server, port);
_smtpClient.EnableSsl = sslEnable;
_smtpClient.Credentials = new System.Net.NetworkCredential(username, password);//用户名和密码
_smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;//指定电子邮件发送方式
_smtpClient.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(m_SendCompleted);
_mailMessage = new System.Net.Mail.MailMessage();
_mailMessage.BodyEncoding = Encoding.UTF8;
_mailMessage.IsBodyHtml = false;
_mailMessage.BodyEncoding = Encoding.UTF8;
_mailMessage.Priority = System.Net.Mail.MailPriority.High;//优先级
_mailMessage.From = new System.Net.Mail.MailAddress(fromAddress, displayName, Encoding.UTF8);
}
#endregion
#region 私有函数
///
/// SmtpClient异步发送完成时回调
///
///
///
private void m_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
if (m_OnSendCompleted != null)
{
this.m_OnSendCompleted.Invoke(sender, e);
}
}
#endregion
#region 公共属性
///
/// 邮件发送异步完成回调事件
///
public event EventHandler SendAsyncCompleted
{
add { m_OnSendCompleted += value; }
remove { m_OnSendCompleted -= value; }
}
///
/// 发件人信息
///
public System.Net.Mail.MailAddress From
{
get { return _mailMessage.From; }
set { _mailMessage.From = value; }
}
///
/// 邮件主题
///
public string Subject
{
get { return _mailMessage.Subject; }
set { _mailMessage.Subject = value; }
}
///
/// 邮件内容
///
public string Body
{
get { return _mailMessage.Body; }
set { _mailMessage.Body = value; }
}
public Encoding BodyEncoding
{
get { return _mailMessage.BodyEncoding; }
set { _mailMessage.BodyEncoding = value; }
}
///
/// 是否为html内容
///
public bool IsBodyHtml
{
get { return _mailMessage.IsBodyHtml; }
set { _mailMessage.IsBodyHtml = value; }
}
///
/// 邮件优先级:低、正常、紧急,默认为 正常
///
public System.Net.Mail.MailPriority Priority
{
get { return _mailMessage.Priority; }
set { _mailMessage.Priority = value; }
}
///
/// 收件人信息
///
public System.Net.Mail.MailAddressCollection To
{
get { return _mailMessage.To; }
}
///
/// 抄送人信息
///
public System.Net.Mail.MailAddressCollection CC
{
get { return _mailMessage.CC; }
}
#endregion
#region 公共函数
///
/// 添加附件
///
///附件的路径集合
public void AddAttachments(IEnumerable paths)
{
foreach (var item in paths)
{
var data = new System.Net.Mail.Attachment(item, System.Net.Mime.MediaTypeNames.Application.Octet);
var disposition = data.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(item);
disposition.ModificationDate = File.GetLastWriteTime(item);
disposition.ReadDate = File.GetLastAccessTime(item);
_mailMessage.Attachments.Add(data);
}
}
///
/// 添加内联附件
/// 不显示在附件里,直接可以用id显示在html内容中,一般用于图片附件
/// 可以用文件id嵌入html
///
///附件的路径集合
public void AddAttachmentsInside(IEnumerable paths)
{
foreach (var item in paths)
{
var data = new System.Net.Mail.Attachment(item, System.Net.Mime.MediaTypeNames.Application.Octet);
var disposition = data.ContentDisposition;
data.ContentDisposition.CreationDate = File.GetCreationTime(item);
data.ContentDisposition.ModificationDate = File.GetLastWriteTime(item);
data.ContentDisposition.ReadDate = File.GetLastAccessTime(item);
data.ContentId = System.IO.Path.GetFileNameWithoutExtension(item);
_mailMessage.Attachments.Add(data);
}
}
///
/// 清除附件
///
public void ClearAttachments()
{
_mailMessage.Attachments.Clear();
}
///
/// 发送邮件(同步方法,发送异常时抛出)
///
/// 收件人
public void Send(string toEmail)
{
Send(new System.Net.Mail.MailAddress(toEmail, toEmail));
}
///
/// 发送邮件(同步方法,发送异常时抛出)
///
/// 收件人
public void Send(System.Net.Mail.MailAddress toEmailObj)
{
Send(new[] { toEmailObj });
}
///
/// 批量发送邮件(同步方法,发送异常时抛出)
///
/// 收件人集合
public void Send(IEnumerable toEmailObjList)
{
_mailMessage.To.Clear();
foreach (var item in toEmailObjList)
{
_mailMessage.To.Add(item);
}
_smtpClient.Send(_mailMessage);
}
///
/// 发送邮件(异步方法,发送异常时回调中返回)
///
/// 收件人
///
public Task SendAsync(string toEmail)
{
return SendAsync(new System.Net.Mail.MailAddress(toEmail, toEmail));
}
///
/// 发送邮件(异步方法,发送异常时回调中返回)
///
/// 收件人
///
public Task SendAsync(System.Net.Mail.MailAddress toEmailObj)
{
return SendAsync(new[] { toEmailObj });
}
///
/// 批量发送邮件(异步方法,发送异常时回调中返回)
///
/// 收件人集合
///
public Task SendAsync(IEnumerable toEmailObjList)
{
_mailMessage.To.Clear();
foreach (var item in toEmailObjList)
{
_mailMessage.To.Add(item);
}
return _smtpClient.SendMailAsync(_mailMessage);
}
///
/// 发送邮件(异步方法,发送异常时回调中返回)
///
/// 收件人
///
public void SendAsync(string toEmail, object userToken)
{
SendAsync(new System.Net.Mail.MailAddress(toEmail, toEmail), userToken);
}
///
/// 发送邮件(异步方法,发送异常时回调中返回)
///
/// 收件人
///
public void SendAsync(System.Net.Mail.MailAddress toEmailObj, object userToken)
{
SendAsync(new[] { toEmailObj }, userToken);
}
///
/// 批量发送邮件(异步方法,发送异常时回调中返回)
///
/// 收件人集合
///
public void SendAsync(IEnumerable toEmailObjList, object userToken)
{
_mailMessage.To.Clear();
foreach (var item in toEmailObjList)
{
_mailMessage.To.Add(item);
}
_smtpClient.SendAsync(_mailMessage, userToken);
}
#endregion
}
}
以上两个类函数的调用基本一致,写的比较简单,调用方式这里就不举例了!


![[发送邮件] System.Web.Mail 与 System.Net.Mail 发送邮件的一些区别和使用 [发送邮件] System.Web.Mail 与 System.Net.Mail 发送邮件的一些区别和使用](http://www.mshxw.com/aiimages/31/955420.png)
