在Web下开发,我想实现异步发送邮件的功能,比如说,在客户成功提交了一个订单时,程序首先保存订单,然后把这些数据发送邮件给管理员和客户,并向数据库插入发送邮件的记录,客户的数量可能是一个也可能很多,然后报告说订单提交成功。如果不用异步方式,那么当给很多客户发送邮件的时候就很耗时,用户就要等很久才能看到成功提示,因此我想,在保存了订单数据后,就用另一个线程来发送邮件,从而当前线程立即就可以向用户反馈订单提交成功的提示信息。   发邮件和插入发送记录的过程是否可以用异步实现?BackgroundWorker 是否可以用于web开发?  
不知应怎样实现?希望有点示例代码,谢谢!

解决方案 »

  1.   

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Collections;
    using System.Net;
    using System.Net.Mail;
    using System.ComponentModel;
    namespace SendLiWu
    {
        public class GmailSmtpEmail
        {
            /// <summary>
            /// 返回为值表示发送成功
            /// </summary>
            private bool mailSent = false;
            /// <summary>
            /// Gmail的用户名:如: [email protected]
            /// </summary>
            private string username = "[email protected]";
            /// <summary>
            /// Gmail的密码
            /// </summary>
            private string password = "!123456789";
            /// <summary>
            /// Gmail的发送邮件服务器
            /// </summary>
            private string Host = "smtp.gmail.com";
            /// <summary>
            /// 端口号
            /// </summary>
            private int Port = 587;
           /// <summary>
           /// 发送Email要使用的编码
           /// </summary>
            private Encoding encoding=Encoding.GetEncoding("utf-8");
            /// <summary>
            /// 设置正文内容是否是包含Html的格式
            /// </summary>
            private bool bodyhtml=false;        /// <summary>
            /// 设置电子邮件的优先级
            /// </summary>
            private MailPriority Priority = MailPriority.High;
            /// <summary>
            /// 是否使用套接字层安全加密连接
            /// </summary>
            private bool Ssl = true;
            /// <summary>
            /// 发送Email要使用的编码
            /// </summary>
            private string errormessage = "";
            public string ErrorMessage
            {
                get { return errormessage; }
            }
            public Encoding Encoding
            {
                get { return encoding; }
                set { encoding = value; }
            }
            /// <summary>
            /// 设置正文内容是否是包含Html的格式
            /// </summary>
            public bool BodyHtml
            {
                get { return bodyhtml; }
                set { bodyhtml = value; }
            }        /// <summary>
            /// 设置电子邮件的优先级
            /// </summary>
            public MailPriority priority
            {
                get { return Priority; }
                set { Priority = value; }
            }
            /// <summary>
            /// 发送单个Email
            /// </summary>
            /// <param name="Subject">主题</param>
            /// <param name="Body">内容</param>
            /// <param name="displayname">显示名</param>
            /// <param name="addressee">收件人的Email地址</param>
            public void SendMail(string Subject, string Body,string displayname, string addressee)
            {
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                msg.To.Add(addressee);
                msg.From = new MailAddress(username, displayname,encoding);
                msg.Subject =Subject;
                msg.SubjectEncoding = encoding;
                msg.Body =Body;
                msg.BodyEncoding =encoding;
                msg.IsBodyHtml =bodyhtml;
                msg.Priority = Priority;            //Add the Creddentials
                SmtpClient client = new SmtpClient();
                client.Credentials = new System.Net.NetworkCredential(username,password);
                client.Port =Port;//or use 587            
                client.Host =Host;
                client.EnableSsl = Ssl;
                client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
                object userState = msg;
                try
                {
                    //you can also call client.Send(msg)
                    client.SendAsync(msg, userState);
                }
                catch (System.Net.Mail.SmtpException ex)
                {
                    mailSent = false;
                    this.errormessage = ex.Message;
                    throw new Exception(ex.Message, ex);
                }
            }
            /// <summary>
            /// 发送一个或者多个的Email
            /// </summary>
            /// <param name="Subject">主题</param>
            /// <param name="Body">内容</param>
            /// <param name="displayname">显示名</param>
            /// <param name="emaillist">收件人Email的列表</param>
            public void SendMail(string Subject, string Body, string displayname, string[] emaillist)
            {
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                for (int i = 0; i <= emaillist.Length - 1; i++)
                {
                    msg.To.Add(emaillist[i].ToString());
                }
                msg.From = new MailAddress(username, displayname, encoding);
                msg.Subject = Subject;
                msg.SubjectEncoding = encoding;
                msg.Body = Body;
                msg.BodyEncoding = encoding;
                msg.IsBodyHtml = bodyhtml;
                msg.Priority = Priority;            //Add the Creddentials
                SmtpClient client = new SmtpClient();
                client.Credentials = new System.Net.NetworkCredential(username, password);
                client.Port = Port;//or use 587            
                client.Host = Host;
                client.EnableSsl = Ssl;
                client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
                object userState = msg;
                try
                {
                    //you can also call client.Send(msg)
                    client.SendAsync(msg, userState);
                }
                catch (System.Net.Mail.SmtpException ex)
                {
                    this.errormessage = ex.Message;
                }
            }
            void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
            {
                MailMessage mail = (MailMessage)e.UserState;
                string subject = mail.Subject;
                if (e.Cancelled)
                {
                    mailSent = false;
                }
                if (e.Error != null)
                {
                    mailSent = false;
                }
                mailSent = true;
            }
        }}注:1,以上是对于WindForm发送Email的类2,如果要变成对于Web发送Email的类把  client.SendAsync(msg, userState);改写成 client.Send(msg, userState);
      

  2.   

    这个Email程序是采用异步来发送Email
    采用Gmail的邮件发送系统
      

  3.   

    Gmail的邮件发送服务器在国外,可以会比较慢,建议用雅虎的邮件发送服务器来发送,相对会快一些,不过月租要10元引用来源:http://awfer1.blog.163.com/blog/
      

  4.   

    谢谢awfer1 
    我需要用异步实现,因为每发一封邮件,还要插入一次数据库,所以要用异步。