C# 邮件发送方法【webMail方式】

在C#中发送邮件的方式有2种,一种是使用webmail方式进行发送,另外一种就是采用netmail发送的方式,在采用这2种方式发送邮件时,如果采用公用的邮件服务器(如126邮件服务器,Sina的邮件服务器)都是需要授权认证才能够发送,如果是采用Gmail的话,还会有每天发送邮件的数量等限制。这2种方式是经过我测试通过了的代码,只需要将邮件的用户名和密码修改成自己的即可,同时也可以修改邮件服务器,改成自己配置的邮件服务器。

/// <summary>
    /// 发送Email(带验证,采用微软新推荐的方式)
    /// </summary>
    /// <param>收件Email</param>
    /// <param>抄送Email</param>
    /// <param>标题</param>
    /// <param>内容</param>
    /// <param>邮箱验证帐号(与web.config里配置的帐号要一样)</param>
    /// <param>发信人邮箱,要与UserName对应</param>
    /// <param>错误消息</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");

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wydpdx.html