C#邮件发送代码实现(MailSender.cs)
来源:互联网 发布:淘宝客定向计划 编辑:程序博客网 时间:2024/05/28 14:56
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.ComponentModel;
using System.Net;
using System.Net.Mail;
using System.Text.RegularExpressions;
namespace home.Common
{
/**
* 邮件发送代码实现(MailSender.cs)
* @auther JiahaiWu 2011-08-14
*/
public class MailSender
{
//邮件发送状态标记量 (0表示初始状态,1表示发送中 ,2表示发送成功 ,-1表示发送失败)
private int mailSendStatus = ORIGINAL;
//设定最小延迟等待时间 (3秒)
public static int waitSeconds = 2000;
//状态标记常量定义
public const int ORIGINAL = 0;
public const int SENDING = 1;
public const int SUCCESS = 2;
public const int FAILED = -1;
public const int CANCELED = -2;
//即时消息缓存字段
private string senderMessage = null;
public int MailSendStatus
{
get
{
return mailSendStatus;
}
}
private string SenderMessage
{
get { return senderMessage; }
}
/// <summary>
/// 异步发送回调方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e">异步发送状态参数</param>
/// @auther JiahaiWu 2011-08-14
private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string)e.UserState;
if (e.Cancelled)
{
senderMessage = "[" + token + "] Send canceled.";
mailSendStatus = CANCELED;
}
if (e.Error != null)
{
senderMessage = "[{" + token + "}] {" + e.Error.ToString() + "}";
mailSendStatus = FAILED;
}
else
{
mailSendStatus = SUCCESS;
senderMessage = "Email send Success.";
}
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="client">smtpClient发送设置</param>
/// <param name="from">发件者邮件地址</param>
/// <param name="password">发件人认证密码</param>
/// <param name="message">发送消息对象</param>
/// <returns>异步发送线程号</returns>
/// @auther JiahaiWu 2011-08-14
private string SendMail(SmtpClient client, MailAddress from, string password, MailMessage message)
{
string token = "MS_" + System.DateTime.Now.ToString("HHmmss") + (new Random()).Next();
//不使用默认凭证,注意此句必须放在client.Credentials的上面
client.UseDefaultCredentials = false;
//指定用户名、密码
client.Credentials = new NetworkCredential(from.Address, password);
//邮件通过网络发送到服务器
client.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
client.SendAsync(message, token);
Thread.Sleep(waitSeconds);
}
catch (Exception ex)
{
throw new Exception("发送失败!" + ex.Message);
}
finally
{
//及时释放占用的资源
message.Dispose();
}
return token;
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="fromEmail">发送者邮箱地址</param>
/// <param name="fromPsaaWord">发送者邮箱密码</param>
/// <param name="toEmail">收件人邮箱地址</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件主要内容</param>
/// <param name="smtpHost">smtp邮件发送服务器地址</param>
/// <param name="port">smtp发送端口,默认为25</param>
/// <param name="attachmentsPath">邮件附件(无附件时为null)</param>
/// <returns>异步发送线程号</returns>
/// @auther JiahaiWu 2011-08-14
public string SendMail(string fromEmail, string fromPassword, object toEmail, string subject, string body,string smtpHost,short port=25,string[] attachmentsPath = null)
{
//发件人地址
MailAddress from = new MailAddress(fromEmail);
//邮件主题、内容
MailMessage message = null;
if (toEmail is ICollection<Object> && (toEmail as ICollection<Object>).Count>0)
{
ICollection<Object> toEmailCollection = toEmail as ICollection<Object>;
if (toEmail is MailAddressCollection)
{
MailAddress to = toEmailCollection.ElementAt(0) as MailAddress;
message = new MailMessage(from, to);
for(int i=1;i<toEmailCollection.Count;i++)
message.Bcc.Add(toEmailCollection.ElementAt(i) as MailAddress);
}
else
{
MailAddress to = new MailAddress(toEmailCollection.ElementAt(0).ToString());
message = new MailMessage(from, to);
for (int i = 1; i < toEmailCollection.Count; i++)
message.Bcc.Add(toEmailCollection.ElementAt(i).ToString());
}
}
else // toEmail as string
{
//收件人地址
MailAddress to = new MailAddress(toEmail.ToString());
//邮件主题、内容
message = new MailMessage(from, to);
}
//主题
message.Subject = subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
//内容
message.Body = body;
message.BodyEncoding = System.Text.Encoding.UTF8;
//在有附件的情况下添加附件
try
{
if (attachmentsPath != null && attachmentsPath.Length > 0)
{
Attachment attachFile = null;
foreach (string path in attachmentsPath)
{
if (System.IO.File.Exists(path))
{
attachFile = new Attachment(path);
message.Attachments.Add(attachFile);
}
else
senderMessage = "warn: the attachment @path=" + path + " not exist!";
}
}
}
catch (Exception err)
{
throw new Exception("在添加附件时有错误:" + err);
}
SmtpClient client = new SmtpClient(smtpHost,port);
return SendMail(client, from, fromPassword,message);
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="fromEmail">发送者邮箱地址</param>
/// <param name="fromPsaaWord">发送者邮箱密码</param>
/// <param name="toEmail">收件人邮箱地址</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件主要内容</param>
/// <param name="smtpHost">smtp邮件发送服务器地址</param>
/// <param name="port">smtp发送端口,默认为25</param>
/// <param name="attachmentsPath">邮件附件(无附件时为null)</param>
/// <returns>邮件发送返回状态码</returns>
/// @auther JiahaiWu 2011-08-14
public int SendMailWithCheck(string fromEmail, string fromPassword, object toEmail, string subject, string body, string smtpHost, short port = 25, string[] attachmentsPath=null)
{
try
{
if (!Regex.IsMatch(fromEmail, @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
{
senderMessage = "参数fromEmail格式不正确!";
mailSendStatus = FAILED;
}
if (toEmail is string && !Regex.IsMatch(toEmail.ToString(), @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
{
senderMessage = "参数toEmail格式不正确!";
mailSendStatus = FAILED;
}
if (subject.Trim() == "")
{
senderMessage = "不支持无主题的邮件!";
mailSendStatus = FAILED;
}
if (body.Trim() == "")
{
senderMessage = "不支持无内容的邮件!";
mailSendStatus = FAILED;
}
if (mailSendStatus != FAILED)
{
SendMail(fromEmail, fromPassword, toEmail, subject, body,smtpHost,port,attachmentsPath);
}
}
catch (Exception ex)
{
mailSendStatus = FAILED;
senderMessage = ex.Message;
}
return mailSendStatus;
}
/// <summary>
/// 发送邮件静态调用方法
/// </summary>
/// <param name="fromEmail">发送者邮箱地址</param>
/// <param name="fromPsaaWord">发送者邮箱密码</param>
/// <param name="toEmail">收件人邮箱地址</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件主要内容</param>
/// <param name="smtpHost">smtp邮件发送服务器地址</param>
/// <param name="port">smtp发送端口,默认为25</param>
/// <param name="attachmentsPath">邮件附件(无附件时为null)</param>
/// <returns>发送状态对象</returns>
/// @auther JiahaiWu 2011-08-14
public static MailResult Send(string fromEmail, string fromPassword, object toEmail, string subject, string body, string smtpHost, short port = 25, string[] attachmentsPath = null)
{
MailSender mailSender = new MailSender();
MailResult res = new MailResult();
res.code = mailSender.SendMailWithCheck(fromEmail, fromPassword, toEmail, subject, body, smtpHost, port, attachmentsPath);
res.message = mailSender.SenderMessage;
return res;
}
/// <summary>
/// 发送邮件静态调用方法
/// </summary>
/// <param name="mailInfo">邮件发送配置信息</param>
/// <param name="toEmail">收件人邮箱地址</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件主要内容</param>
/// <param name="attachmentsPath">邮件附件(无附件时为null)</param>
/// <returns>发送状态对象</returns>
/// @auther JiahaiWu 2011-08-14
public static MailResult Send(MailInfo mailInfo, object toEmail, string subject, string body, string[] attachmentsPath = null)
{
MailSender mailSender = new MailSender();
MailResult res = new MailResult();
res.code = mailSender.SendMailWithCheck(mailInfo.sender, mailInfo.password, toEmail, subject, body, mailInfo.smtpHost, mailInfo.port, attachmentsPath);
res.message = mailSender.SenderMessage;
System.Diagnostics.Debug.WriteLine("邮件发送 @code=" + res.code + " @message=" + res.message);
return res;
}
}
public class MailResult{
public int code;
public string message;
}
public class MailInfo
{
public string sender;
public string password;
public string smtpHost;
public short port = 25;
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.ComponentModel;
using System.Net;
using System.Net.Mail;
using System.Text.RegularExpressions;
namespace home.Common
{
/**
* 邮件发送代码实现(MailSender.cs)
* @auther JiahaiWu 2011-08-14
*/
public class MailSender
{
//邮件发送状态标记量 (0表示初始状态,1表示发送中 ,2表示发送成功 ,-1表示发送失败)
private int mailSendStatus = ORIGINAL;
//设定最小延迟等待时间 (3秒)
public static int waitSeconds = 2000;
//状态标记常量定义
public const int ORIGINAL = 0;
public const int SENDING = 1;
public const int SUCCESS = 2;
public const int FAILED = -1;
public const int CANCELED = -2;
//即时消息缓存字段
private string senderMessage = null;
public int MailSendStatus
{
get
{
return mailSendStatus;
}
}
private string SenderMessage
{
get { return senderMessage; }
}
/// <summary>
/// 异步发送回调方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e">异步发送状态参数</param>
/// @auther JiahaiWu 2011-08-14
private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string)e.UserState;
if (e.Cancelled)
{
senderMessage = "[" + token + "] Send canceled.";
mailSendStatus = CANCELED;
}
if (e.Error != null)
{
senderMessage = "[{" + token + "}] {" + e.Error.ToString() + "}";
mailSendStatus = FAILED;
}
else
{
mailSendStatus = SUCCESS;
senderMessage = "Email send Success.";
}
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="client">smtpClient发送设置</param>
/// <param name="from">发件者邮件地址</param>
/// <param name="password">发件人认证密码</param>
/// <param name="message">发送消息对象</param>
/// <returns>异步发送线程号</returns>
/// @auther JiahaiWu 2011-08-14
private string SendMail(SmtpClient client, MailAddress from, string password, MailMessage message)
{
string token = "MS_" + System.DateTime.Now.ToString("HHmmss") + (new Random()).Next();
//不使用默认凭证,注意此句必须放在client.Credentials的上面
client.UseDefaultCredentials = false;
//指定用户名、密码
client.Credentials = new NetworkCredential(from.Address, password);
//邮件通过网络发送到服务器
client.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
client.SendAsync(message, token);
Thread.Sleep(waitSeconds);
}
catch (Exception ex)
{
throw new Exception("发送失败!" + ex.Message);
}
finally
{
//及时释放占用的资源
message.Dispose();
}
return token;
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="fromEmail">发送者邮箱地址</param>
/// <param name="fromPsaaWord">发送者邮箱密码</param>
/// <param name="toEmail">收件人邮箱地址</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件主要内容</param>
/// <param name="smtpHost">smtp邮件发送服务器地址</param>
/// <param name="port">smtp发送端口,默认为25</param>
/// <param name="attachmentsPath">邮件附件(无附件时为null)</param>
/// <returns>异步发送线程号</returns>
/// @auther JiahaiWu 2011-08-14
public string SendMail(string fromEmail, string fromPassword, object toEmail, string subject, string body,string smtpHost,short port=25,string[] attachmentsPath = null)
{
//发件人地址
MailAddress from = new MailAddress(fromEmail);
//邮件主题、内容
MailMessage message = null;
if (toEmail is ICollection<Object> && (toEmail as ICollection<Object>).Count>0)
{
ICollection<Object> toEmailCollection = toEmail as ICollection<Object>;
if (toEmail is MailAddressCollection)
{
MailAddress to = toEmailCollection.ElementAt(0) as MailAddress;
message = new MailMessage(from, to);
for(int i=1;i<toEmailCollection.Count;i++)
message.Bcc.Add(toEmailCollection.ElementAt(i) as MailAddress);
}
else
{
MailAddress to = new MailAddress(toEmailCollection.ElementAt(0).ToString());
message = new MailMessage(from, to);
for (int i = 1; i < toEmailCollection.Count; i++)
message.Bcc.Add(toEmailCollection.ElementAt(i).ToString());
}
}
else // toEmail as string
{
//收件人地址
MailAddress to = new MailAddress(toEmail.ToString());
//邮件主题、内容
message = new MailMessage(from, to);
}
//主题
message.Subject = subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
//内容
message.Body = body;
message.BodyEncoding = System.Text.Encoding.UTF8;
//在有附件的情况下添加附件
try
{
if (attachmentsPath != null && attachmentsPath.Length > 0)
{
Attachment attachFile = null;
foreach (string path in attachmentsPath)
{
if (System.IO.File.Exists(path))
{
attachFile = new Attachment(path);
message.Attachments.Add(attachFile);
}
else
senderMessage = "warn: the attachment @path=" + path + " not exist!";
}
}
}
catch (Exception err)
{
throw new Exception("在添加附件时有错误:" + err);
}
SmtpClient client = new SmtpClient(smtpHost,port);
return SendMail(client, from, fromPassword,message);
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="fromEmail">发送者邮箱地址</param>
/// <param name="fromPsaaWord">发送者邮箱密码</param>
/// <param name="toEmail">收件人邮箱地址</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件主要内容</param>
/// <param name="smtpHost">smtp邮件发送服务器地址</param>
/// <param name="port">smtp发送端口,默认为25</param>
/// <param name="attachmentsPath">邮件附件(无附件时为null)</param>
/// <returns>邮件发送返回状态码</returns>
/// @auther JiahaiWu 2011-08-14
public int SendMailWithCheck(string fromEmail, string fromPassword, object toEmail, string subject, string body, string smtpHost, short port = 25, string[] attachmentsPath=null)
{
try
{
if (!Regex.IsMatch(fromEmail, @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
{
senderMessage = "参数fromEmail格式不正确!";
mailSendStatus = FAILED;
}
if (toEmail is string && !Regex.IsMatch(toEmail.ToString(), @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
{
senderMessage = "参数toEmail格式不正确!";
mailSendStatus = FAILED;
}
if (subject.Trim() == "")
{
senderMessage = "不支持无主题的邮件!";
mailSendStatus = FAILED;
}
if (body.Trim() == "")
{
senderMessage = "不支持无内容的邮件!";
mailSendStatus = FAILED;
}
if (mailSendStatus != FAILED)
{
SendMail(fromEmail, fromPassword, toEmail, subject, body,smtpHost,port,attachmentsPath);
}
}
catch (Exception ex)
{
mailSendStatus = FAILED;
senderMessage = ex.Message;
}
return mailSendStatus;
}
/// <summary>
/// 发送邮件静态调用方法
/// </summary>
/// <param name="fromEmail">发送者邮箱地址</param>
/// <param name="fromPsaaWord">发送者邮箱密码</param>
/// <param name="toEmail">收件人邮箱地址</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件主要内容</param>
/// <param name="smtpHost">smtp邮件发送服务器地址</param>
/// <param name="port">smtp发送端口,默认为25</param>
/// <param name="attachmentsPath">邮件附件(无附件时为null)</param>
/// <returns>发送状态对象</returns>
/// @auther JiahaiWu 2011-08-14
public static MailResult Send(string fromEmail, string fromPassword, object toEmail, string subject, string body, string smtpHost, short port = 25, string[] attachmentsPath = null)
{
MailSender mailSender = new MailSender();
MailResult res = new MailResult();
res.code = mailSender.SendMailWithCheck(fromEmail, fromPassword, toEmail, subject, body, smtpHost, port, attachmentsPath);
res.message = mailSender.SenderMessage;
return res;
}
/// <summary>
/// 发送邮件静态调用方法
/// </summary>
/// <param name="mailInfo">邮件发送配置信息</param>
/// <param name="toEmail">收件人邮箱地址</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件主要内容</param>
/// <param name="attachmentsPath">邮件附件(无附件时为null)</param>
/// <returns>发送状态对象</returns>
/// @auther JiahaiWu 2011-08-14
public static MailResult Send(MailInfo mailInfo, object toEmail, string subject, string body, string[] attachmentsPath = null)
{
MailSender mailSender = new MailSender();
MailResult res = new MailResult();
res.code = mailSender.SendMailWithCheck(mailInfo.sender, mailInfo.password, toEmail, subject, body, mailInfo.smtpHost, mailInfo.port, attachmentsPath);
res.message = mailSender.SenderMessage;
System.Diagnostics.Debug.WriteLine("邮件发送 @code=" + res.code + " @message=" + res.message);
return res;
}
}
public class MailResult{
public int code;
public string message;
}
public class MailInfo
{
public string sender;
public string password;
public string smtpHost;
public short port = 25;
}
}
- C#邮件发送代码实现(MailSender.cs)
- C# - MailSender 邮件发送组件源代码 (支持ESMTP, 附件)
- C# - MailSender 邮件发送组件源代码 (支持ESMTP, 附件)
- C#-MailSender邮件发送组件源代码
- 使用Spring的MailSender发送邮件
- spring的MailSender发送普通邮件
- C#发送邮件代码
- C#邮件发送代码
- C#发送邮件代码
- C#邮件发送代码
- C#发送邮件代码
- C#发送邮件代码
- C#发送邮件代码
- C#邮件发送代码
- C#发送邮件代码
- C#发送邮件代码
- C#发送邮件代码
- C#发送邮件代码
- 最棒的程序代码,不是程序代码
- 【线段树】线段树学习贴(持续更新)
- 第一篇
- spark下_3D翻转特效(一)
- 面试题总结 - C 语言 - 数据声明(data declaration)
- C#邮件发送代码实现(MailSender.cs)
- 初学Android ,程序运行不起来的问题多多
- 自定义session扫描器
- ZOJ2876 POJ3630 HDU1671 Phone List,静态Trie树
- 利用JAVA读写rtf文档
- 堆排序算法
- 面试题总结 - C 语言 - 关键字(keywords)
- 中秋节与程序员
- spark下_3D两扇门特效