c#利用webmail邮件系统发送邮件示例分享

 更新时间:2014年01月20日 16:21:59   作者:  
在C#中发送邮件的方式有2种,一种是使用webmail方式进行发送,另外一种就是采用netmail发送的方式,这篇文章介绍了c#使用webmail方式发送邮件示例,大家参考使用吧

在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文件中配置如下:

相关文章

  • C#创建Excel多级分组的方法

    C#创建Excel多级分组的方法

    这篇文章主要为大家详细介绍了C#创建Excel多级分组的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-12-12
  • 深入多线程之:Reader与Write Locks(读写锁)的使用详解

    深入多线程之:Reader与Write Locks(读写锁)的使用详解

    本篇文章是对Reader与Write Locks(读写锁)的使用进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • C#实现闹钟AlarmClock实例代码

    C#实现闹钟AlarmClock实例代码

    这篇文章主要介绍了C#实现闹钟AlarmClock实例代码,很实用的功能,需要的朋友可以参考下
    2014-08-08
  • unity实现摄像头跟随

    unity实现摄像头跟随

    把这个脚本赋给你的摄像机,再把游戏角色赋给character变量,之后就能实现摄像机平滑的跟随player在地球的任一角落了。有需要的小伙伴可以参考下。
    2015-03-03
  • Task提高异步执行效率技巧

    Task提高异步执行效率技巧

    这篇文章介绍了Task提高异步执行效率的技巧,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-04-04
  • 浅谈对c# 面向对象的理解

    浅谈对c# 面向对象的理解

    这篇文章主要介绍了个人对c# 面向对象的理解,算是一个入门篇吧,给需要的小伙伴参考下,抛砖引玉。
    2014-12-12
  • 解析c#操作excel后关闭excel.exe的方法

    解析c#操作excel后关闭excel.exe的方法

    C#和Asp.net下excel进程一被打开,有时就无法关闭,尤其是website.对关闭该进程有过GC、release等方法,但这些方法并不是在所有情况下均适用
    2013-07-07
  • C#中遍历DataSet数据集对象实例

    C#中遍历DataSet数据集对象实例

    这篇文章主要介绍了C#中遍历DataSet数据集对象实例,经常忘记如何操作DataSet,这里记下来并分享,让需要的朋友可以参考下
    2014-08-08
  • C#多线程开发实战记录之线程基础

    C#多线程开发实战记录之线程基础

    线程是一个独立的运行单元,每个进程内部有多个线程,每个线程可以各自同时执行指令,每个线程有自己独立的栈,但是与进程内的其他线程共享内存,这篇文章主要给大家介绍了关于C#多线程开发实战记录之线程基础的相关资料,需要的朋友可以参考下
    2021-09-09
  • C#异步调用示例详解

    C#异步调用示例详解

    这篇文章主要为大家详细介绍了C#异步调用的示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-06-06

最新评论