昨日在asp.net下做一个异步发邮件的功能,参照了MSDN的解决办法,但是发现了在aspx中调用它还需要要注意要将页面的 Async设置为 true才可以。是因为.net发邮件的时候如果采用异步的方式,它所在的上下文必须允许异步调用机制,在asp.net 中,它的上下文就可以理解为httpcontent,也就是它所在的页面。完整代码如下:
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Mail;
using System.Configuration;
using System.Text;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
using System.Net.Mail;
namespace MailAsnc
...{
/** <summary>
/// PandaHall网站发送Mail功能类
/// </summary>
public class MailHelper
...{
/** <summary>
/// 发送Email功能函数
/// </summary>
/// <param name="from">发送人</param>
/// <param name="to">接收人</param>
/// <param name="cc">抄送</param>
/// <param name="subject">主题</param>
/// <param name="body">内容</param>
/// <param name="isBodyHtml">是否是HTML格式Mail</param>
/// <returns>是否成功</returns>
public static bool SendEmail(string from, string to, string cc, string subject, string body, bool isBodyHtml)
...{
try
...{
Debug.WriteLine(DateTime.Now);
//设置smtp
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["SMTPServer"]);
//设置帐户
smtp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["SMTPServerUser"], ConfigurationManager.AppSettings["SMTPServerPassword"]);
//开一个Message
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
//主题
mail.Subject = subject;
mail.SubjectEncoding = System.Text.Encoding.GetEncoding("GB2312");
mail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");
//发送
mail.From = new System.Net.Mail.MailAddress(from);
//邮件等级
mail.Priority = System.Net.Mail.MailPriority.High;
//设置邮件格式
mail.IsBodyHtml = isBodyHtml;
//主题内容
mail.Body = body;
//设置发送对象
mail.To.Add(to);
//如果有抄送人就抄送,没有就不送
if (cc != null && cc != string.Empty)
...{
//抄送
mail.CC.Add(cc);
}
//发送Email
smtp.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
object userState = mail;
smtp.SendAsync(mail, userState);
return true;
}
catch (Exception ex)
...{
return false;
}
}
public static void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
...{
bool mailSent = true;
System.Net.Mail.MailMessage mail = (System.Net.Mail.MailMessage)e.UserState;
string subject = mail.Subject;
string content = mail.Body;
if (e.Cancelled)
...{
mailSent = false;
}
if (e.Error != null)
...{
mailSent = false;
}
if (!mailSent)
...{
string file = "Send Mail/Send Mail test asnc Error " + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
StringBuilder sb = new StringBuilder();
sb.Append("Send Failed! " );
sb.Append("Subject :"+subject+" ");
sb.Append("Content :" + content);
sb.Append("Exception :" + e.Error.ToString());
WriteLog.Write(sb.ToString(), file);
}
else
...{
string file = "Send Mail/Send Mail test asnc Error " + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
StringBuilder sb = new StringBuilder();
sb.Append("Send Sucess! ");
sb.Append("Subject :" + subject + " ");
sb.Append("Content :" + content);
WriteLog.Write(sb.ToString(), file);
}
}
}
}