[置頂] C# 郵件發送方法【webMail方式】

來源:互聯網
上載者:User

在C#中發送郵件的方式有2種,一種是使用webmail方式進行發送,另外一種就是採用netmail發送的方式,在採用這2種方式發送郵件時,如果採用公用的郵件伺服器(如126郵件伺服器,Sina的郵件伺服器)都是需要授權認證才能夠發送,如果是採用Gmail的話,還會有每天發送郵件的數量等限制。這2種方式是經過我測試通過了的代碼,只需要將郵件的使用者名稱和密碼修改成自己的即可,同時也可以修改郵件伺服器,改成自己配置的郵件伺服器。

/// <summary>
    /// 發送Email(帶驗證,採用微軟新推薦的方式)
    /// </summary>
    /// <param name="strTo">收件Email</param>
    /// <param name="strCc">抄送Email</param>
    /// <param name="strSubject">標題</param>
    /// <param name="strBody">內容</param>
    /// <param name="UserName">郵箱驗證帳號(與web.config裡配置的帳號要一樣)</param>
    /// <param name="from">發信人郵箱,要與UserName對應</param>
    /// <param name="strErrorMsg">錯誤訊息</param>
    /// <returns></returns>
    public static bool WebSendEmail(string strTo, string strCc, string strSubject, string strBody, ref string strErrorMsg)
    {
        System.Web.Mail.MailMessage message = new System.Web.Mail.MailMessage();
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

        bool bState = false;
        string strSMTPServer = "";

        try
        {
            strSMTPServer = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SMTP"]);
            strSMTPServer = strSMTPServer == "" ? "localhost" : strSMTPServer;

            string strFromAddr = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["FromAddress"]);
            if (reg.IsMatch(strFromAddr))
            {
                message.From = strFromAddr;
            }
            else
            {
                throw new Exception("The Email Address is wrong,Please reset the Email Address in the web.config file !");
            }

            string strTemp = "";
            foreach (string str in strTo.Split(';'))
            {
                if (reg.IsMatch(str))
                    if (!strTemp.Contains(str))
                        strTemp += str + ";";
            }

            message.Cc = "";
            foreach (string str in strCc.Split(';'))
            {
                if (reg.IsMatch(str))
                    if (!message.Cc.Contains(str))
                        message.Cc += str + ";";
            }

            message.Subject = strSubject;
            message.BodyFormat = System.Web.Mail.MailFormat.Html;

            message.Body ="<html><body>UtilMailMessage001"+ strBody+"- success</body></html>" ;
            //下面這塊是載入附件的方法
            MailAttachment attachment1 =new MailAttachment(@"d:\My Documents\test1.doc");
            MailAttachment attachment2 =new MailAttachment("d:\\Documents\\test2.doc");
            message.Attachments.Add(attachment1);
            message.Attachments.Add(attachment2);

            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");

            //這裡的郵箱帳號和密碼一定要和下面設定檔中設定的郵箱的帳號和密碼一致
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "xxxxxxxxx");//郵箱帳號,比如Test11@126.com帳號為:Test11
            message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "xxxxxxxx");//郵箱密碼
            //這個是指明郵件伺服器的連接埠,可以不指定
            //message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "25");
     

            foreach (string str in strTemp.Split(';'))
            {
                if (reg.IsMatch(str))
                {
                    message.To = str;
                    message.BodyEncoding = System.Text.Encoding.UTF8;
                    System.Web.Mail.SmtpMail.SmtpServer = strSMTPServer;
                   
                    System.Web.Mail.SmtpMail.Send(message);
                }
            }

            bState = true;
        }
        catch (Exception ex)
        {
            System.IO.File.AppendAllText("C:\\Mail_Log.ini", string.Format("{0:yyyy/MM/dd HH:mm:ss}\r\n{1}\r\n\r\n", DateTime.Now, ex.Message));
            bState = false;
            strErrorMsg = ex.Message;
        }

        return bState;
    }

//測試發送郵件

protected void btnSend_Click(object sender, EventArgs e)
    {
        try
        {
           
            Email.SendEmail("xxxxxx@163.com", "", "Test Email", "Test Send Email");
         
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }

郵件在webconfig檔案中配置如下:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.