コード例 #1
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="receivers">收件人邮箱列表</param>
        /// <param name="senderAddress">发件人邮箱</param>
        /// <param name="senderPasscode">发件人密码</param>
        /// <param name="emailBody">邮件内容</param>
        /// <param name="emailTitle">邮件标题</param>
        /// <param name="enableSsl">是否启用SSL</param>
        /// <param name="emailAttachments">邮件附件</param>
        public static void SendEmail(List <string> receivers, string senderAddress, string senderPasscode, string emailBody, string emailTitle, bool enableSsl, params FileInfo[] emailAttachments)
        {
            if (string.IsNullOrEmpty(senderAddress) || !RegularUtil.RegexEmail(senderAddress))
            {
                throw new ArgumentException("请填写有效的发件人邮箱", "senderAddress");
            }
            //定义一个邮件对象
            MailMessage mailMessage = new MailMessage();

            //循环收件人列表添加收件人
            foreach (string receiveAddress in receivers)
            {
                if (string.IsNullOrEmpty(receiveAddress) || !RegularUtil.RegexEmail(receiveAddress))
                {
                    continue;
                }
                mailMessage.To.Add(receiveAddress);
            }
            if (mailMessage.To.Count <= 0)
            {
                throw new ArgumentException("请填写收件人");
            }
            //添加发件人
            mailMessage.From = new MailAddress(senderAddress, DeviceUtil.GetSystemUserName());
            //设置邮件标题
            mailMessage.Subject = emailTitle;
            //设置邮件内容
            mailMessage.Body = emailBody;
            //默认使用HTML格式的邮件内容
            mailMessage.IsBodyHtml = true;
            //邮件内容编码使用默认编码
            mailMessage.BodyEncoding = Encoding.Default;
            //设置邮件优先级为普通,似乎是过高容易被当成垃圾邮件
            mailMessage.Priority = MailPriority.Normal;
            //如果附件列表不为空且包含附件
            if (emailAttachments != null && emailAttachments.Length > 0)
            {
                //循环附件列表添加附件
                foreach (FileInfo attachmentFile in emailAttachments)
                {
                    //定义一个附件对象并设置附件路径,附件的创建,修改,访问时间
                    Attachment         attachment         = new Attachment(attachmentFile.FullName);
                    ContentDisposition contentDisposition = attachment.ContentDisposition;
                    contentDisposition.CreationDate     = attachmentFile.CreationTime;
                    contentDisposition.ModificationDate = attachmentFile.LastWriteTime;
                    contentDisposition.ReadDate         = attachmentFile.LastAccessTime;
                    mailMessage.Attachments.Add(attachment);
                }
            }
            //定义一个Smtp客户端对象
            SmtpClient smtpClient = new SmtpClient();
            //获取第一个收件人的地址
            string firstReciever = receivers.Where(p => p.IndexOf('@') > -1).FirstOrDefault();
            //计算收件人的Smtp协议
            int    hostStart = firstReciever.IndexOf('@');
            string smtpHost  = string.Format("smtp{0}", firstReciever.Substring(hostStart, firstReciever.Length - hostStart).Replace('@', '.'));

            //设置smtp协议
            smtpClient.Host = smtpHost;
            //设置是否启用SSL
            smtpClient.EnableSsl = enableSsl;
            //设置Smtp客户端使用默认的身份验证方式
            smtpClient.UseDefaultCredentials = true;
            //设置Smtp客户端的用户密码,用于发送邮件
            smtpClient.Credentials = new NetworkCredential(mailMessage.From.Address, senderPasscode);
            //设置客户端发送邮件的方式为网络的方式
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            try
            {
                //开始发送邮件
                smtpClient.SendMailAsync(mailMessage).Wait();
            }
            catch (Exception ex)
            {
                LogUtil.WriteLog(ex);
                //如果错误提示为需要开启SSL并且没有打开SSL
                if (ex.Message == "need EHLO and AUTH first" && !enableSsl)
                {
                    //迭代发送邮件并启用SSL
                    SendEmail(receivers, senderAddress, senderPasscode, emailBody, emailTitle, true, emailAttachments);
                }
                else
                {
                    //否则有可能发件失败了,抛出异常
                    throw ex;
                }
            }
        }