程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 郵件發送方法【webMail方式】

C# 郵件發送方法【webMail方式】

編輯:C#入門知識

在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");//郵箱帳號,比如[email protected]帳號為: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("[email protected]", "", "Test Email", "Test Send Email");
         
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
郵件在webconfig文件中配置如下:

\

摘自 weizhiai12的專欄
 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved