C#实现异步发送邮件的方法
本文实例讲述了C#实现异步发送邮件的方法。分享给大家供大家参考。具体如下:
下面的代码可以实现异步发送邮件,等邮件发送出去后会自动调用回调函数,这样在发送邮件时就不会卡住程序不动了
MailMessagem=newMailMessage ("item@jb51.net", "raja@jb51.net", "Thisisthesubjectfortheauthorizedemail.", "Thisisthebodyoftheauthorizedmail!..."); //Sendthemessageusingauthorization SmtpClientclient=newSmtpClient("smtp.jb51.net"); client.Credentials=newNetworkCredential("user","password"); client.EnableSsl=true; //Addtheeventhandler client.SendCompleted+=newSendCompletedEventHandler(mail_SendCompleted); //Sendthemessageasynchronously client.SendAsync(m,null); //ToCancelthesend //client.SendAsyncCancel(); voidmail_SendCompleted(objectsender,AsyncCompletedEventArgse) { if(e.Cancelled) Console.WriteLine("Messagecancelled"); elseif(e.Error!=null) Console.WriteLine("Error:"+e.Error.ToString()); else Console.WriteLine("Messagesent"); }
希望本文所述对大家的C#程序设计有所帮助。