異步發送郵件C#代碼

ybny 9年前發布 | 1K 次閱讀 C#

下面的代碼可以實現異步發送郵件,等郵件發送出去后會自動調用回調函數,這樣在發送郵件時就不會卡住程序不動了

MailMessage m = new MailMessage
   ("item@sharejs.com",
    "raja@sharejs.com",
    "This is the subject for the authorized email.",
    "This is the body of the authorized mail!...");

// Send the message using authorization
SmtpClient client = new SmtpClient("smtp.sharejs.com");
client.Credentials = new NetworkCredential("user", "password");
client.EnableSsl = true;

// Add the event handler
client.SendCompleted += new SendCompletedEventHandler(mail_SendCompleted);

// Send the message asynchronously
client.SendAsync(m, null);

// To Cancel the send
//client.SendAsyncCancel();
void mail_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
    if (e.Cancelled)
        Console.WriteLine("Message cancelled");
    else if (e.Error != null)
        Console.WriteLine("Error: " + e.Error.ToString());
    else
        Console.WriteLine("Message sent");
}

 本文由用戶 ybny 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!