首页 > 代码库 > MVC发送邮件

MVC发送邮件

<>

技术分享

发送邮件报错说明


发送邮件 假设发送人的邮箱username与邮箱password都没有填写错误:假设报:參数或变量中有语法错误。 server响应为:mail from address must be same as authorization user错误,问题可能出在authorization user  没授权。假设是QQ邮箱。那么仅仅要进入QQ邮箱。QQ邮箱:设置---账户  找到POP3/IMAP/SMTP服务  都开启。这时候发现能够发送邮件了。

技术分享

假设报:SMTP server要求安全连接或client未通过身份验证。

server响应为:Must issue a STARTTLS command first. 可能出现的问题是发送邮件的serverport(smtp.Port)配置错误。 比如:smtp.Port = 25

假设报:命令顺序不对。

server响应为:Error: need EHLO and AUTH first ! 非常有可能是发件人邮箱的username写错了;比如:(smtp.Credentials = new NetworkCredential("邮箱的username", "发件人邮箱password");

假设报:參数或变量中有语法错误。 server响应为:mail from address must be same as authorization user  非常有可能是发件人邮箱的password错误了:比如:(smtp.Credentials = new NetworkCredential("邮箱的username", "发件人邮箱password");

==============================================================================


web.config配置文件

  <appSettings>
    <!--2015-06-26 Create-->
    <!-- Smtp server -->
    <add key="SmtpHost" value="http://www.mamicode.com/smtp.qq.com" />
    <!-- Smtp serverport -->
    <add key="SmtpPort" value="http://www.mamicode.com/587" />
    <!--发送者 Email 地址-->
    <add key="FromEmailAddress" value="http://www.mamicode.com/wowo@qq.com" />
    <!--发送者 Email password-->
    <add key="FormEmailPassword" value="http://www.mamicode.com/123456789" />

    <add key="ToEmailListString" value="http://www.mamicode.com/123@qq.com;456@qq.com"/>
    <add key="CcEmailListString" value="http://www.mamicode.com/CBA@qq.com"/>
    <add key="BccEmailListString" value="http://www.mamicode.com/NBA@qq.com"/>
  </appSettings>


Home控制器

using CFPS_Redesign;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC发送邮件測试.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult SendEmail()
        {
            EmailHelper eh = new EmailHelper("邮件的主题", "你什么时候过来吃饭?");
            if (eh.SendEmail())
            {
                return View();
            }
            else
            {
                return Content("on");
            }           
        }

    }
}

EmailHelper邮件发送类

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace CFPS_Redesign
{
    /// <summary>
    /// Author      : Bin
    /// Date        : 2015-06-26
    /// Description : 邮件发送辅助类
    /// </summary>
    public class EmailHelper
    {
        #region [ 属性(发送Email相关) ]
        private string _SmtpHost = string.Empty;
        private int _SmtpPort = -1;
        private string _FromEmailAddress = string.Empty;
        private string _FormEmailPassword = string.Empty;
        private string _ToEmailListString = string.Empty;
        private string _CcEmailListString = string.Empty;
        private string _BccEmailListString = string.Empty;

        /// <summary>
        /// smtp server 
        /// </summary>
        public string SmtpHost
        {
            get
            {
                if (string.IsNullOrEmpty(_SmtpHost))
                {
                    _SmtpHost = ConfigurationManager.AppSettings["SmtpHost"];
                }
                return _SmtpHost;
            }
        }
        /// <summary>
        /// smtp serverport  默觉得25
        /// </summary>
        public int SmtpPort
        {
            get
            {
                if (_SmtpPort == -1)
                {
                    if (!int.TryParse(ConfigurationManager.AppSettings["SmtpPort"], out _SmtpPort))
                    {
                        _SmtpPort = 25;
                    }
                }
                return _SmtpPort;
            }
        }
        /// <summary>
        /// 发送者 Eamil 地址
        /// </summary>
        public string FromEmailAddress
        {
            get
            {
                if (string.IsNullOrEmpty(_FromEmailAddress))
                {
                    _FromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"];
                }
                return _FromEmailAddress;
            }
        }

        /// <summary>
        /// 发送者 Eamil password
        /// </summary>
        public string FormEmailPassword
        {
            get
            {
                if (string.IsNullOrEmpty(_FormEmailPassword))
                {
                    _FormEmailPassword = ConfigurationManager.AppSettings["FormEmailPassword"];
                }
                return _FormEmailPassword;
            }
        }

        #endregion

        #region [ 属性(邮件相关) ]
        /// <summary>
        /// 收件人 Email 列表,多个邮件地址之间用 半角逗号“,”或者分号“;”,或者竖线“|” 等符号分隔开
        /// </summary>
        public string ToEmailListString
        {
            get
            {
                if (string.IsNullOrEmpty(_ToEmailListString))
                {
                    return ConfigurationManager.AppSettings["ToEmailListString"];
                }
                return _ToEmailListString;
            }
            set
            {
                this._ToEmailListString = value;
            }
        }
        /// <summary>
        /// 邮件的抄送者,支持群发,多个邮件地址之间用 半角逗号“,”或者分号“;”,或者竖线“|” 等符号分隔开
        /// </summary>
        public string CcEmailListString
        {
            get
            {
                if (string.IsNullOrEmpty(this._CcEmailListString))
                {
                    return ConfigurationManager.AppSettings["CcEmailListString"];
                }
                return _CcEmailListString;
            }
            set
            {
                this._CcEmailListString = value;
            }

        }
        /// <summary>
        /// 邮件的密送者,支持群发,多个邮件地址之间用 半角逗号“,”或者分号“;”,或者竖线“|” 等符号分隔开
        /// </summary>
        public string BccEmailListString
        {
            get
            {
                if (string.IsNullOrEmpty(_BccEmailListString))
                {
                    return ConfigurationManager.AppSettings["BccEmail"];
                }
                return _BccEmailListString;
            }
            set
            {
                this._BccEmailListString = value;
            }

        }
        /// <summary>
        /// 邮件标题
        /// </summary>
        public string Subject { get; set; }
        /// <summary>
        /// 邮件正文
        /// </summary>
        public string EmailBody { get; set; }

        private bool _IsBodyHtml;
        /// <summary>
        /// 邮件正文是否为Html格式
        /// </summary>
        public bool IsBodyHtml
        {
            get { return _IsBodyHtml; }
            set { _IsBodyHtml = value; }
        }

        /// <summary>
        /// 附件列表
        /// </summary>
        public List<Attachment> AttachmentList { get; set; }
        #endregion


        #region [ 构造函数 ]
        /// <summary>
        /// 构造函数(EmailBody默觉得html格式)
        /// </summary>
        /// <param name="subject">邮件标题</param>
        /// <param name="emailBody">邮件正文</param>
        public EmailHelper(string subject, string emailBody)
        {
            this.Subject = subject;
            this.IsBodyHtml = true;
            this.EmailBody = emailBody;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="subject">邮件标题</param>
        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>
        /// <param name="emailBody">邮件正文</param>
        public EmailHelper(string subject, bool isBodyHtml, string emailBody)
        {
            this.Subject = subject;
            this.IsBodyHtml = IsBodyHtml;
            this.EmailBody = emailBody;
        }

        /// <summary>
        /// 构造函数(EmailBody默觉得html格式)
        /// </summary>
        /// <param name="subject">邮件标题</param>
        /// <param name="emailBody">邮件正文</param>
        /// <param name="attachmentList">附件列表</param>
        public EmailHelper(string subject, string emailBody, List<Attachment> attachmentList)
        {
            this.Subject = subject;
            this.EmailBody = emailBody;
            this.AttachmentList = attachmentList;
            this.IsBodyHtml = true;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="subject">邮件标题</param>
        /// <param name="emailBody">邮件正文</param>
        /// <param name="isBodyEmail">邮件正文是否为Html格式</param>
        /// <param name="attachmentList">附件列表</param>
        public EmailHelper(string subject, string emailBody, bool isBodyEmail, List<Attachment> attachmentList)
        {
            this.Subject = subject;
            this.EmailBody = emailBody;
            this.AttachmentList = attachmentList;
            
        }

        /// <summary>
        /// 构造函数 (EmailBody默觉得html格式)
        /// </summary>
        /// <param name="toList">收件人列表字符串</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="emailBody">邮件正文</param>
        public EmailHelper(string toEmailListString, string subject, string emailBody)
        {
            this.ToEmailListString = toEmailListString;
            this.Subject = subject;
            this.EmailBody = emailBody;
            this.IsBodyHtml = true;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="toList">收件人列表字符串</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>
        /// <param name="emailBody">邮件正文</param>
        public EmailHelper(string toEmailListString, string subject, bool isBodyHtml, string emailBody)
        {
            this.ToEmailListString = toEmailListString;
            this.Subject = subject;
            this.IsBodyHtml = isBodyHtml;
            this.EmailBody = emailBody;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="toEmailListString">收件人列表字符串</param>
        /// <param name="ccEmailListString">抄送人列表字符串</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>
        /// <param name="emailBody">邮件正文</param>
        public EmailHelper(string toEmailListString, string ccEmailListString, string subject, bool isBodyHtml, string emailBody)
        {
            this.ToEmailListString = toEmailListString;
            this.CcEmailListString = ccEmailListString;            
            this.Subject = subject;
            this.IsBodyHtml = isBodyHtml;
            this.EmailBody = emailBody;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="toEmailListString">收件人列表字符串</param>
        /// <param name="ccEmailListString">抄送人列表字符串</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>
        /// <param name="emailBody">邮件正文</param>
        /// <param name="attachmentList">附件列表</param>
        public EmailHelper(string toEmailListString, string ccEmailListString, string subject, bool isBodyHtml, string emailBody, List<Attachment> attachmentList)
        {
            this.ToEmailListString = toEmailListString;
            this.CcEmailListString = ccEmailListString;           
            this.Subject = subject;
            this.IsBodyHtml = isBodyHtml;
            this.EmailBody = emailBody;
            this.AttachmentList = attachmentList;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="toEmailListString">收件人列表字符串</param>
        /// <param name="ccEmailListString">抄送人列表字符串</param>
        /// <param name="bccEmailListString">密送人列表字符串</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>
        /// <param name="emailBody">邮件正文</param>
        public EmailHelper(string toEmailListString, string ccEmailListString, string bccEmailListString, string subject, bool isBodyHtml, string emailBody)
        {
            this.ToEmailListString = toEmailListString;
            this.CcEmailListString = ccEmailListString;
            this.BccEmailListString = bccEmailListString;
            this.Subject = subject;
            this.IsBodyHtml = isBodyHtml;
            this.EmailBody = emailBody;
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="toEmailListString">收件人列表字符串</param>
        /// <param name="ccEmailListString">抄送人列表字符串</param>
        /// <param name="bccEmailListString">密送人列表字符串</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>
        /// <param name="emailBody">邮件正文</param>
        /// <param name="attachmentList">附件列表</param>
        public EmailHelper(string toEmailListString, string ccEmailListString, string bccEmailListString, string subject, bool isBodyHtml, string emailBody, List<Attachment> attachmentList)
        {
            this.ToEmailListString = toEmailListString;
            this.CcEmailListString = ccEmailListString;
            this.BccEmailListString = bccEmailListString;
            this.Subject = subject;
            this.IsBodyHtml = isBodyHtml;
            this.EmailBody = emailBody;
            this.AttachmentList = attachmentList;
        }
        #endregion

        #region [ 发送邮件 ]
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <returns></returns>
        public bool SendEmail()
        {
            try
            {
                MailMessage mm = new MailMessage(); //实例化一个邮件类
                mm.Priority = MailPriority.Normal; //邮件的优先级,分为 Low, Normal, High。通经常使用 Normal就可以
                mm.From = new MailAddress(this.FromEmailAddress, "管理员", Encoding.GetEncoding("GB2312"));

                //收件人
                if (!string.IsNullOrEmpty(this.ToEmailListString))
                {
                    string[] toEmailArray = this.ToEmailListString.Split(new char[] { ‘;‘, ‘,‘, ‘|‘, ‘ ‘ }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string toEmail in toEmailArray)
                    {
                        mm.To.Add(toEmail.Trim());
                    }

                }
                //抄送人
                if (!string.IsNullOrEmpty(this.CcEmailListString))
                {
                    string[] CcEmailArray = this.CcEmailListString.Split(new char[] { ‘;‘, ‘,‘, ‘|‘, ‘ ‘ }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string ccEmail in CcEmailArray)
                    {
                        mm.CC.Add(ccEmail.Trim());
                    }
                }
                //密送人
                if (!string.IsNullOrEmpty(this.BccEmailListString))
                {
                    string[] BccEmailArray = this.BccEmailListString.Split(new char[] { ‘;‘, ‘,‘, ‘|‘, ‘ ‘ }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string bccEmail in BccEmailArray)
                    {
                        mm.Bcc.Add(bccEmail.Trim());
                    }
                }

                mm.Subject = this.Subject;                            //邮件标题
                mm.SubjectEncoding = Encoding.GetEncoding("GB2312");  //这里很重要。假设你的邮件标题包括中文。这里一定要指定。否则对方收到的极有可能是乱码。
                mm.IsBodyHtml = this.IsBodyHtml;                      //邮件正文是否是HTML格式
                mm.BodyEncoding = Encoding.GetEncoding("GB2312");     //邮件正文的编码, 设置不对。 接收者会收到乱码
                mm.Body = this.EmailBody;                             //邮件正文

                //邮件附件
                if (this.AttachmentList != null && this.AttachmentList.Count > 0)
                {
                    foreach (Attachment attachment in this.AttachmentList)
                    {
                        mm.Attachments.Add(attachment);
                    }
                }

                SmtpClient smtp = new SmtpClient();                 //实例化一个SmtpClient
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;   //将smtp的出站方式设为 Network
                smtp.EnableSsl = false;                             //smtpserver是否启用SSL加密
                smtp.Host = this.SmtpHost;                          //指定 smtp server地址

                //smtp.Port = this.SmtpPort;                        //指定 smtp server的port。默认是25。假设採用默认port。可省去
                //smtp.UseDefaultCredentials = true;                //假设你的SMTPserver不须要身份认证。则使用以下的方式,只是。眼下基本没有不须要认证的了

                smtp.Credentials = new NetworkCredential(this.FromEmailAddress, this.FormEmailPassword);    //假设须要认证,则用这样的方式

                //发送邮件,假设不返回异常, 则大功告成了。
                smtp.Send(mm);

                return true;
            }
            catch (Exception e)
            {
               return false;                
            }
       
        }
        #endregion
    }
}


??

MVC发送邮件