asp.net发邮件的小例子

发布时间:2019-07-15编辑:脚本学堂
分享一个asp.net中发送邮件的例子,使用smtp发送邮件,指定发件人、收件人、标题、内容等。有需要的朋友参考下。

本节内容:
asp.net代码发送邮件

说明:以下代码,只测试了单封邮件的发送,群发的方法,大家可以自行扩展下。

例子:
   

复制代码 代码示例:

/// <summary>
    /// 单发Email

    /// </summary>
    /// <param name="from">发信人地址</param>
    /// <param name="to">收信人地址</param>
    /// <param name="title">标题</param>
    /// <param name="body">内容</param>
    /// <returns></returns>
    public static  string sendEmail(string to, string title, string body)
    {
        try
        {
            MailMessage m_message = new MailMessage();

            m_message.From = new MailAddress("*@126.com");

            m_message.To.Add(new MailAddress(to));

            m_message.Subject = title;

            m_message.Body = body;

            SmtpClient m_smtpClient = createClient();

            m_smtpClient.Send(m_message);
            return "发送成功";
        } // www.jb200.com
        catch (Exception e)
        {
            return e.Message;
        }
    }

    /// <summary>
    /// 群发Email

    /// </summary>
    /// <param name="from">发信人地址</param>
    /// <param name="to">收信人地址列表</param>
    /// <param name="title">标题</param>
    /// <param name="body">内容</param>
    /// <returns></returns>
    public static  string sendEmail(string[] to, string title, string body)
    {
        try
        {
            MailMessage m_message = new MailMessage();
            m_message.From = new MailAddress("*@126.com");
           foreach (string s in to)
            {
                m_message.To.Add(new MailAddress(s));
            }

            m_message.Subject = title;

            m_message.Body = body;

            SmtpClient m_smtpClient =createClient();

            m_smtpClient.Send(m_message);
            return "发送成功";
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }


    public static  SmtpClient createClient()
    {
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.126.com";
        smtp.Port = 25;

        smtp.UsedefaultCredentials = true;//不能和帐号顺序颠倒,否则出错。
        smtp.Credentials = new System.Net.NetworkCredential("*@126.com", "******");
        return smtp;
    }