本文实例讲述了c#使用系统方法发送异步邮件。分享给大家供大家参考,具体如下:
项目背景:
最近在对几年前的一个项目进行重构,发现发送邮件功能需要一定的时间来处理,而由于发送是同步的因此导致在发送邮件时无法执行后续的操作
实际上发送邮件后只需要将发送结果写入系统日志即可对其他业务没有任何影响,因此决定将发送邮件操作更改为异步的
由于使用的是c#的邮件类库,而c#本身已经提供了异步发送的功能即只需要将send方法更改为sendasync即可,更改方法名并不难但发送后再写入日志就有点难了
因为项目中发送邮件是单独的组件,所以我不可能在发送邮件类库中直接添加写入日志操作(不在同一个类库,网络和msdn上的例子都是同一组件下)
但c#可以使用委托将方法作为参数来传递的,因此我就可以在发送邮件的方法中添加一个回调方法,在异步发送邮件后再执行回调方法即可
完整代码:
/******************************************************************
* 创建人:htl
* 说明:c# 发送异步邮件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( "开始异步发送邮件,时间:" + datetime.now.tostring(dateformat));
new mailhelper().sendasync( "send async email test" , "this is send async email test" , "huangyuan413026@163.com" , emailcompleted);
console.writeline( "邮件正在异步发送,时间:" + datetime.now.tostring(dateformat));
console.readkey();
console.writeline();
}
/// <summary>
/// 邮件发送后的回调方法
/// </summary>
/// <param name="message"></param>
static void emailcompleted( string message)
{
//延时1秒
system.threading.thread.sleep(1000);
console.writeline();
console.writeline( "邮件发送结果:\r\n" + (message == "true" ? "邮件发送成功" : "邮件发送失败" ) + ",时间:" + datetime.now.tostring(dateformat));
//写入日志
}
}
/// <summary>
/// 发送邮件类
/// </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,
};
}
}
//回调方法
action< string > actionsendcompletedcallback = null ;
///// <summary>
///// 使用异步发送邮件
///// </summary>
///// <param name="subject">主题</param>
///// <param name="body">内容</param>
///// <param name="to">接收者,以,分隔多个接收者</param>
//// <param name="_actincompletedcallback">邮件发送后的回调方法</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 ;
//发送邮件回调方法
actionsendcompletedcallback = _actincompletedcallback;
smtpclient.sendcompleted += new sendcompletedeventhandler(sendcompletedcallback);
try
{
smtpclient.sendasync(mailmessage, "true" ); //异步发送邮件,如果回调方法中参数不为"true"则表示发送失败
}
catch (exception e)
{
throw new exception(e.message);
}
finally
{
smtpclient = null ;
mailmessage = null ;
}
}
/// <summary>
/// 异步操作完成后执行回调方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void sendcompletedcallback( object sender, system.componentmodel.asynccompletedeventargs e)
{
//同一组件下不需要回调方法,直接在此写入日志即可
//写入日志
//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;
//执行回调方法
actionsendcompletedcallback(message);
}
}
}
运行效果图如下:
希望本文所述对大家c#程序设计有所帮助。
dy("nrwz");
查看更多关于C#使用系统方法发送异步邮件完整实例的详细内容...