C#使用系統(tǒng)方法發(fā)送異步郵件完整實(shí)例
本文實(shí)例講述了C#使用系統(tǒng)方法發(fā)送異步郵件。分享給大家供大家參考,具體如下:
項目背景:
最近在對幾年前的一個項目進(jìn)行重構(gòu),發(fā)現(xiàn)發(fā)送郵件功能需要一定的時間來處理,而由于發(fā)送是同步的因此導(dǎo)致在發(fā)送郵件時無法執(zhí)行后續(xù)的操作
實(shí)際上發(fā)送郵件后只需要將發(fā)送結(jié)果寫入系統(tǒng)日志即可對其他業(yè)務(wù)沒有任何影響,因此決定將發(fā)送郵件操作更改為異步的
由于使用的是C#的郵件類庫,而C#本身已經(jīng)提供了異步發(fā)送的功能即只需要將Send方法更改為SendAsync即可,更改方法名并不難但發(fā)送后再寫入日志就有點(diǎn)難了
因為項目中發(fā)送郵件是單獨(dú)的組件,所以我不可能在發(fā)送郵件類庫中直接添加寫入日志操作(不在同一個類庫,網(wǎng)絡(luò)和MSDN上的例子都是同一組件下)
但C#可以使用委托將方法作為參數(shù)來傳遞的,因此我就可以在發(fā)送郵件的方法中添加一個回調(diào)方法,在異步發(fā)送郵件后再執(zhí)行回調(diào)方法即可
完整代碼:
/******************************************************************
* 創(chuàng)建人:HTL
* 說明:C# 發(fā)送異步郵件Demo
*******************************************************************/
using System;
using System.Net.Mail;
namespace SendAsyncEmailTest
{
class Program
{
const string dateFormat = "yyyy-MM-dd :HH:mm:ss:ffffff";
static void Main(string[] args)
{
Console.WriteLine("開始異步發(fā)送郵件,時間:" + DateTime.Now.ToString(dateFormat));
new MailHelper().SendAsync("Send Async Email Test", "This is Send Async Email Test", "huangyuan413026@163.com", emailCompleted);
Console.WriteLine("郵件正在異步發(fā)送,時間:" + DateTime.Now.ToString(dateFormat));
Console.ReadKey();
Console.WriteLine();
}
/// <summary>
/// 郵件發(fā)送后的回調(diào)方法
/// </summary>
/// <param name="message"></param>
static void emailCompleted(string message)
{
//延時1秒
System.Threading.Thread.Sleep(1000);
Console.WriteLine();
Console.WriteLine("郵件發(fā)送結(jié)果:\r\n" + (message == "true" ? "郵件發(fā)送成功" : "郵件發(fā)送失敗") + ",時間:" + DateTime.Now.ToString(dateFormat));
//寫入日志
}
}
/// <summary>
/// 發(fā)送郵件類
/// </summary>
public class MailHelper
{
public delegate int MethodDelegate(int x, int y);
private readonly int smtpPort = 25;
readonly string SmtpServer = "smtp.baidu.com";
private readonly string UserName = "support@baidu.com";
readonly string Pwd = "baidu.com";
private readonly string AuthorName = "BaiDu";
public string Subject { get; set; }
public string Body { get; set; }
public string Tos { get; set; }
public bool EnableSsl { get; set; }
MailMessage GetClient
{
get
{
if (string.IsNullOrEmpty(Tos)) return null;
MailMessage mailMessage = new MailMessage();
//多個接收者
foreach (string _str in Tos.Split(','))
{
mailMessage.To.Add(_str);
}
mailMessage.From = new System.Net.Mail.MailAddress(UserName, AuthorName);
mailMessage.Subject = Subject;
mailMessage.Body = Body;
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
mailMessage.Priority = System.Net.Mail.MailPriority.High;
return mailMessage;
}
}
SmtpClient GetSmtpClient
{
get
{
return new SmtpClient
{
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(UserName, Pwd),
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
Host = SmtpServer,
Port = smtpPort,
EnableSsl = EnableSsl,
};
}
}
//回調(diào)方法
Action<string> actionSendCompletedCallback = null;
///// <summary>
///// 使用異步發(fā)送郵件
///// </summary>
///// <param name="subject">主題</param>
///// <param name="body">內(nèi)容</param>
///// <param name="to">接收者,以,分隔多個接收者</param>
//// <param name="_actinCompletedCallback">郵件發(fā)送后的回調(diào)方法</param>
///// <returns></returns>
public void SendAsync(string subject, string body, string to, Action<string> _actinCompletedCallback)
{
if (string.IsNullOrEmpty(to)) return;
Tos = to;
SmtpClient smtpClient = GetSmtpClient;
MailMessage mailMessage = GetClient;
if (smtpClient == null || mailMessage == null) return;
Subject = subject;
Body = body;
EnableSsl = false;
//發(fā)送郵件回調(diào)方法
actionSendCompletedCallback = _actinCompletedCallback;
smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
try
{
smtpClient.SendAsync(mailMessage, "true");//異步發(fā)送郵件,如果回調(diào)方法中參數(shù)不為"true"則表示發(fā)送失敗
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
smtpClient = null;
mailMessage = null;
}
}
/// <summary>
/// 異步操作完成后執(zhí)行回調(diào)方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SendCompletedCallback(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
//同一組件下不需要回調(diào)方法,直接在此寫入日志即可
//寫入日志
//return;
if (actionSendCompletedCallback == null) return;
string message = string.Empty;
if (e.Cancelled)
{
message = "異步操作取消";
}
else if (e.Error != null)
{
message = (string.Format("UserState:{0},Message:{1}", (string)e.UserState, e.Error.ToString()));
}
else
message = (string)e.UserState;
//執(zhí)行回調(diào)方法
actionSendCompletedCallback(message);
}
}
}
運(yùn)行效果圖如下:

更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#窗體操作技巧匯總》、《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#程序設(shè)計之線程使用技巧總結(jié)》、《C#操作Excel技巧總結(jié)》、《C#中XML文件操作技巧匯總》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#數(shù)組操作技巧總結(jié)》及《C#面向?qū)ο蟪绦蛟O(shè)計入門教程》
希望本文所述對大家C#程序設(shè)計有所幫助。
相關(guān)文章
在web.config和app.config文件中增加自定義配置節(jié)點(diǎn)的方法
本篇文章主要是對在web.config和app.config文件中增加自定義配置節(jié)點(diǎn)的方法進(jìn)行了詳細(xì)的介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01
c# 模擬串口通信 SerialPort的實(shí)現(xiàn)示例
本文主要介紹了c# 模擬串口通信 SerialPort的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05
C#實(shí)現(xiàn)將PDF轉(zhuǎn)為Excel的方法詳解
通常,PDF格式的文檔能支持的編輯功能不如office文檔多,針對PDF文檔里面有表格數(shù)據(jù)的,如果想要編輯表格里面的數(shù)據(jù),可以將該P(yáng)DF文檔轉(zhuǎn)為Excel格式。本文將介紹如何利用C#實(shí)現(xiàn)PDF轉(zhuǎn)Excel,需要的可以參考一下2022-04-04
C#使用百度Ueditor富文本框?qū)崿F(xiàn)上傳文件
這篇文章主要為大家詳細(xì)介紹了C#如何使用百度Ueditor富文本框?qū)崿F(xiàn)上傳文件(圖片,視頻等),文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-07-07

