上方廣告

Lady Kukki 手作糖霜餅乾

2009年1月29日 星期四

傳統發送mail VS 多執行緒發送mail

最近要寫一個電子報發送程式,由於可能同時點選多封郵件同時發送,通常會寫一個function呼叫執行,但可能會因為太多郵件造成超時,因此必須改成多執行緒發送郵件

傳統方式
//發送電子報
protected void SendMail()
{
    try
    {
        MailAddress fromMail = new MailAddress("發信者信箱", "電子報標題", System.Text.Encoding.UTF8);
        MailAddress toMail = new MailAddress("收件者信箱", "收件者姓名");
        MailMessage message = new MailMessage(fromMail, toMail);
        message.Subject = cobEName.Text;
        message.Body = "這裡是電子報發送的內容";
        message.IsBodyHtml = true;
        message.Headers.Add("Disposition-Notification-To", "<回傳的mail>");
        SmtpClient mailClient = new SmtpClient("SMTPServer");
        mailClient.Credentials = new System.Net.NetworkCredential(txtLoginID.Text, txtLoginPwd.Text);//取得或設定驗證資料
        //mailClient.EnableSsl = true;//指定 SmtpClient 是否使用 SSL 加密連線
        //mailClient.Port = 587;
        mailClient.Send(message);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}


多執行緒發送
public delegate string AsyncSendMail(string From, string[] To);

//非同步發送
private void btnAsySend_Click(object sender, EventArgs e)
{
    string[] aryMail = txtTo.Text.Split(',');//收件者信箱
    AsyncSendMail AsySend = new AsyncSendMail(SendMailAsync);
    AsyncCallback AsyBack = new AsyncCallback(SendMailCallBack);
    IAsyncResult isr = AsySend.BeginInvoke(txtFrom.Text, aryMail, AsyBack, AsySend); MessageBox.Show("郵件已加入工作排程,完成後會寄送一封通知信給您,謝謝");
}

public string SendMailAsync(string From, string[] To)
{
    StringBuilder sb = new StringBuilder();
    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sb.AppendFormat("起始時間 - {0} - ", DateTime.Now);
    sb.AppendFormat("總共{0}封郵件 ", To.Length);
    int Success = 0;
    int Failure = 0;
    SmtpClient emailClient = new SmtpClient("SMTPServer");
    emailClient.Credentials = new NetworkCredential("ID", "Pwd");
    sw.Reset();
    sw.Start();
    for (int i = 0; i < To.Length; i++)
    {
        try
        {
            MailMessage message = new MailMessage()
            {
                Body = txtBody.Text,
                BodyEncoding = Encoding.UTF8,
                From = new MailAddress(From),
                IsBodyHtml = true,
                Subject = txtSubject.Text,
                SubjectEncoding = Encoding.UTF8,
            };
            message.Headers.Add("Disposition-Notification-To", "回傳的信箱");
            message.To.Add(To[i]); emailClient.Send(message);
            Success++;
            message.Dispose();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            sb.AppendFormat(" 寄送失敗的郵件 - {0}", To[i]); Failure++; continue;
        }
    }
    sw.Stop();
    emailClient = null;
    sb.AppendFormat("成功郵件數量:{0}失敗郵件數量:{1} ", Success, Failure);
    sb.AppendFormat(" 結束時間 - {0} - ", DateTime.Now);
    sb.AppendFormat(" 總共時數 - {0}小時{1}分{2}秒{3}毫秒", sw.Elapsed.Hours, sw.Elapsed.Minutes, sw.Elapsed.Seconds, sw.Elapsed.Milliseconds);
    return sb.ToString();
}

public void SendMailCallBack(IAsyncResult isr)
{
    AsyncSendMail AsySend = (AsyncSendMail)isr.AsyncState;
    string result = AsySend.EndInvoke(isr);
    SmtpClient emailClient = new SmtpClient("SMTPServer");
    emailClient.Credentials = new NetworkCredential("ID", "PWD");
    MailMessage ResultMail = new MailMessage("回傳的信箱", "回傳的信箱", "郵件寄送完成通知信", result);
    ResultMail.IsBodyHtml = true;
    emailClient.Send(ResultMail);
    emailClient = null;
    ResultMail.Dispose();
}


多執行緒的使用方法來源參考 迷之殿