asp.net发送E-mail-阿里云开发者社区

开发者社区> 安全> 正文

asp.net发送E-mail

简介: 发送电子邮件也是项目开发当中经常用到的功能,这里我整理了一个发送电子邮件(带附件,支持多用户发送,主送、抄送)的类库,供大家参考。

发送电子邮件也是项目开发当中经常用到的功能,这里我整理了一个发送电子邮件(带附件,支持多用户发送,主送、抄送)的类库,供大家参考。

先上两个实体类,用于封装成Mail对象。

    /// <summary>
    /// 发送邮件请求
    /// </summary>
    public class MailRequest
    {
        #region PrivateFields

        /// <summary>
        /// 文件名
        /// </summary>
        private string _fromField;

        /// <summary>
        /// 返送到
        /// </summary>
        private string _toField;

        /// <summary>
        /// 抄送
        /// </summary>
        private string _copyField;

        /// <summary>
        /// 附件
        /// </summary>
        private string _bccField;

        /// <summary>
        /// 标题
        /// </summary>
        private string _subjectField;

        /// <summary>
        /// 发送人名
        /// </summary>
        private string _bodyField;

        /// <summary>
        /// 类容
        /// </summary>
        private MailRequestAttachments[] _attachmentsField;

        #endregion

        /// <summary>
        /// 发送人,多个人以分号;间隔
        /// </summary>
        public string From
        {
            get
            {
                return this._fromField;
            }

            set
            {
                this._fromField = value;
            }
        }

        /// <summary>
        /// 收件人,多个人以分号;间隔
        /// </summary>
        public string To
        {
            get
            {
                return this._toField;
            }

            set
            {
                this._toField = value;
            }
        }

        /// <summary>
        /// 抄送人,多个人以分号;间隔
        /// </summary>
        public string CC
        {
            get
            {
                return this._copyField;
            }

            set
            {
                this._copyField = value;
            }
        }

        /// <summary>
        /// 秘密抄送人,多个人以分号;间隔
        /// </summary>
        public string Bcc
        {
            get
            {
                return this._bccField;
            }

            set
            {
                this._bccField = value;
            }
        }

        /// <summary>
        /// 主题
        /// </summary>
        public string Subject
        {
            get
            {
                return this._subjectField;
            }

            set
            {
                this._subjectField = value;
            }
        }

        /// <summary>
        /// 内容
        /// </summary>
        public string Body
        {
            get
            {
                return this._bodyField;
            }

            set
            {
                this._bodyField = value;
            }
        }

        /// <summary>
        /// 附件列表
        /// </summary>
        public MailRequestAttachments[] Attachments
        {
            get
            {
                return this._attachmentsField;
            }

            set
            {
                this._attachmentsField = value;
            }
        }
    }
    /// <summary>
    /// 发送邮件请求附件
    /// </summary>
    public class MailRequestAttachments
    {
        #region PrivateFields

        /// <summary>
        /// 文件名
        /// </summary>
        private string _fileNameField;

        /// <summary>
        /// 文件内容
        /// </summary>
        private byte[] _fileDataField;

        #endregion

        /// <summary>
        /// 文件名
        /// </summary>
        public string FileName
        {
            get
            {
                return this._fileNameField;
            }

            set
            {
                this._fileNameField = value;
            }
        }

        /// <summary>
        /// 文件内容
        /// </summary>
        public byte[] FileData
        {
            get
            {
                return this._fileDataField;
            }

            set
            {
                this._fileDataField = value;
            }
        }
    }
附件的内容很简单,因为在网络传输当中,是以字节流的形式传输的,因此附件的传输需要转换成字节流数组。

    /// <summary>
    /// 邮件帮助类
    /// </summary>
    public static class MailHelper
    {
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="request">邮件内容对象</param>
        /// <returns>发送邮件所遇到的异常</returns>
        public static string SendMail(MailRequest request)
        {
            try
            {
                MailMessage mail = new MailMessage();

                if (string.IsNullOrEmpty(request.From))
                {
                    request.From = WebConfigurationManager.AppSettings["DefaultMailFrom"];
                }
                mail.From = new MailAddress(request.From);

                PaserMailAddress(request.To, mail.To);
                PaserMailAddress(request.CC, mail.CC);
                PaserMailAddress(request.Bcc, mail.Bcc);

                mail.Subject = request.Subject;
                mail.SubjectEncoding = System.Text.Encoding.UTF8;
                mail.Body = request.Body;
                mail.ReplyTo = new MailAddress(request.From);
                mail.IsBodyHtml = true;

                if (request.Attachments != null && request.Attachments.Length > 0)
                {
                    for (int i = 0; i < request.Attachments.Length; i++)
                    {
                        Attachment mailAttach = new Attachment(ByteArrayToStream(request.Attachments[i].FileData), request.Attachments[i].FileName);

                        mail.Attachments.Add(mailAttach);
                    }
                }

                if (string.IsNullOrEmpty(WebConfigurationManager.AppSettings["SMTPSERVER"]))
                {
                    throw new ApplicationException("邮件服务无效");
                }

                //Smtp Server
                SmtpClient mailClient = new SmtpClient(WebConfigurationManager.AppSettings["SMTPSERVER"]);

                if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["SMTPSERVERPORT"]))
                {
                    //端口号
                    try
                    {
                        mailClient.Port = Int32.Parse(WebConfigurationManager.AppSettings["SMTPSERVERPORT"]);
                    }
                    catch
                    {
                        return "SMTP服务器端口设置错误,端口必须设置为数值型";
                    }
                }

                if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["MAILUSER"]))
                {
                    mailClient.Credentials = new System.Net.NetworkCredential(WebConfigurationManager.AppSettings["MAILUSER"], WebConfigurationManager.AppSettings["MAILUSERPW"]);
                    mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                }
                else
                {
                    mailClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                }

                mailClient.Send(mail);
                mail.Dispose();

                return "邮件发送成功。";
            }
            catch (SmtpFailedRecipientsException e)
            {
                return e.Message;
            }
            catch (SmtpFailedRecipientException e)
            {
                return e.Message;
            }
            catch (SmtpException e)
            {
                return e.Message;
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

        /// <summary>
        /// 解析分解邮件地址
        /// </summary>
        /// <param name="mailAddress">邮件地址</param>
        /// <param name="mailCollection">邮件对象</param>
        private static void PaserMailAddress(string mailAddress, MailAddressCollection mailCollection)
        {
            if (string.IsNullOrEmpty(mailAddress))
            {
                return;
            }

            char[] separator = new char[2] { ',', ';' };
            string[] addressArray = mailAddress.Split(separator);

            foreach (string address in addressArray)
            {
                if (address.Trim() == string.Empty)
                {
                    continue;
                }

                mailCollection.Add(new MailAddress(address));
            }
        }

        /// <summary>
        /// 字节数组转换为流
        /// </summary>
        /// <param name="byteArray">字节数组</param>
        /// <returns>Stream</returns>
        private static Stream ByteArrayToStream(byte[] byteArray)
        {
            MemoryStream mstream = new MemoryStream(byteArray);

            return mstream;
        }
    }
这是一个邮件助手类,定义成static,无需实例化,直接类名.方法名的形式调用。

只需要上述3个类就可以实现发送Email了,由于上面引用的是web.config里面的信息(asp.net等命名空间,如果是winform等需要自己修改一下),这里还需要配置一下web.config,如下所示:

  <appSettings>
    <!--邮件发送配置-->
    <add key="SMTPSERVER" value="smtp.qq.com"/>
    <!--这是服务器邮箱的地址,如果是新浪,则填 smtp.sina.com-->
    <add key="MAILUSER" value="xxx"/>
    <!--注意!这是对应服务器邮箱的账号-->
    <add key="MAILUSERPW" value="yyy"/>
    <!--注意!这是对应服务器邮箱的账号密码-->
  </appSettings>
最后上一个测试方法,在主函数当中或者Page_Load事件中执行即可:

        private void SendEmailExample()
        {
            MailRequest mail = new MailRequest();
            mail.Subject = "hello,this is a e-mail sent by asp.net mailhelper.";//主题
            mail.Body = "hello,this is a e-mail sent by asp.net mailhelper.<a href='http://blog.csdn.net/guwei4037'>欢迎访问我的博客。</a>";//内容
            mail.Bcc = "512122338@qq.com";//秘密抄送人
            mail.From = "345822155@qq.com";//发送人
            mail.CC = "guwei4037@sina.com";//抄送人
            mail.To = "guwei4037@gmail.com";//收件人

            //读取文件到bytes
            FileStream stream = new FileStream(Path.Combine(Server.MapPath("~"), "doc\\test.txt"), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            stream.Close();

            //附件
            MailRequestAttachments attachments = new MailRequestAttachments();
            attachments.FileName = "test.txt";
            attachments.FileData = bytes;
            mail.Attachments = new MailRequestAttachments[] { 
                    attachments
                };

            string sendMainResult = "-1";
            if (!string.IsNullOrEmpty(mail.CC.Replace(";", "")) && !string.IsNullOrEmpty(mail.To.Replace(";", "")))
            {
                sendMainResult = MailHelper.SendMail(mail);
            }
            Response.Write(sendMainResult);
        }
发送邮件成功,附件也能正常打开,而且多个用户都收到了电子邮件。截图为证。


源代码下载,请点击这里。



——————————————————————————————————————————————————————————————————————

最近一个朋友问我说,我上面的这段发送邮件的代码出问题了,出错截图如下:


心想该不是qq邮箱SMTP设置没打开吧,打开邮箱一看是打开的。


注意下面的一段温馨提示:登录第三方客户端时,密码框请输入“授权码”进行验证。难道是qq邮箱的安全机制修改过了?

按照提示,发送了短信,收到了授权码。把原来程序中的发送邮箱账号的明文密码修改成这个授权码,再在程序中加如下两行代码即可。

  mailClient.EnableSsl = true;
  mailClient.UseDefaultCredentials = false;


版权声明:本文首发在云栖社区,遵循云栖社区版权声明:本文内容由互联网用户自发贡献,版权归用户作者所有,云栖社区不为本文内容承担相关法律责任。云栖社区已升级为阿里云开发者社区。如果您发现本文中有涉嫌抄袭的内容,欢迎发送邮件至:developer2020@service.aliyun.com 进行举报,并提供相关证据,一经查实,阿里云开发者社区将协助删除涉嫌侵权内容。

分享:
+ 订阅

云安全开发者的大本营

其他文章