MVC發送郵件

來源:互聯網
上載者:User

標籤:csdn   接收   work   開啟   new   sdn   執行個體化   for   tac   

<>


發送郵件報錯說明


發送郵件 假設發送人的郵箱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="smtp.qq.com" />    <!-- Smtp serverport -->    <add key="SmtpPort" value="587" />    <!--寄件者 Email 地址-->    <add key="FromEmailAddress" value="[email protected]" />    <!--寄件者 Email password-->    <add key="FormEmailPassword" value="123456789" />    <add key="ToEmailListString" value="[email protected];[email protected]"/>    <add key="CcEmailListString" value="[email protected]"/>    <add key="BccEmailListString" value="[email protected]om"/>  </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發送郵件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.