ASP.NET发送邮件(同步、异步)

方法1:这种方法的参数比较固定,发送邮件的参数都已经设定好了

写一个类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Text;

/// <summary>
///发送邮件类
/// </summary>
public class MailService
{
    /// <summary>
    /// 发送邮件的方法(发送单个收件人)
    /// </summary>
    /// <param name="fromMail">源邮件地址</param>
    /// <param name="toMail">目的邮件地址</param>
    /// <param name="loginName">用户名</param>
    /// <param name="pass">密码</param>
    /// <param name="title">发送邮件的标题</param>
    /// <param name="content">发送邮件的内容</param>
    public void SendMail( string fromMail, string toMail, string loginName, string pass, string title, string content)
    {

        MailMessage  mailMessage = new MailMessage();

        SmtpClient client= new SmtpClient();
        //发件人邮箱地址
        //mailMessage.From = new MailAddress(fromMail);
        //收件人邮箱地址
       
mailMessage.To.Add(new MailAddress(toMail));

        //邮件标题编码
        mailMessage.SubjectEncoding = Encoding.UTF8;
        //邮件主题
        mailMessage.Subject = title;
        //邮件内容
        mailMessage.Body = content;
        //邮件内容编码
        mailMessage.BodyEncoding = Encoding.UTF8;
        //设置正文内容是否是包含Html的格式
        mailMessage.IsBodyHtml = true ;
        //发送邮件的优先等级(有效值为High,Low,Normal)
        mailMessage.Priority = MailPriority.Normal;
        //指定发送邮件的服务器地址或IP
        client.Host = @"smtp.163.com";  //固定写

        //client.Host = "smtp." + mailMessage.From.Host;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
        //指定登录服务器的用户名和密码
        client.Credentials = new System.Net.NetworkCredential(loginName, pass);
        //发送邮件
        //client.Send(mailMessage);   //同步发送
        client.SendAsync(mailMessage, mailMessage.To); //异步发送 (异步发送时页面上要加上Async="true" )
    }

    void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {

        if (e.Cancelled)
        {
            System.Web.HttpContext.Current.Response.Write("<script>alert('Sending of email message was cancelled.');</script>");
        }
         if (e.Error == null)
        {
            System.Web.HttpContext.Current.Response.Write("<script>alert('Mail sent successfully');</script>");
         }
        else
        {
            System.Web.HttpContext.Current.Response.Write("<script>alert('Error occured, info=" + e.Error.Message + "');</script>");
        }

    }

   }

如果源发送地址是固定的,那可以在web.config里同配置,代码就会相对减小:

web.config的配置:

<system.net>
    <mailSettings>
      <smtp deliveryMethod="Network" from="your email address">
        <network defaultCredentials="false" host="your eamil ip" port="端口号" userName="your email name" password="your email password"/>
      </smtp>
    </mailSettings>
  </system.net>

上面那个类的SendMail方法的代码就减小为:

    /// <summary>
    /// 发送邮件的方法(发送单个收件人)
    /// </summary>
    /// <param name="toMail">目的邮件地址</param>
    /// <param name="title">发送邮件的标题</param>
    /// <param name="content">发送邮件的内容</param>
    public void SendMail(string toMail,string title, string content)
    {
         //收件人邮箱地址
       
mailMessage.To.Add(new MailAddress(toMail));

        //邮件标题编码
        mailMessage.SubjectEncoding = Encoding.UTF8;
        //邮件主题
        mailMessage.Subject = title;
        //邮件内容
        mailMessage.Body = content;
        //邮件内容编码
        mailMessage.BodyEncoding = Encoding.UTF8;
        //设置正文内容是否是包含Html的格式
        mailMessage.IsBodyHtml = true ;
        //发送邮件的优先等级(有效值为High,Low,Normal)
        mailMessage.Priority = MailPriority.Normal;
        client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
        //发送邮件
        //client.Send(mailMessage);   //同步发送
        client.SendAsync(mailMessage, mailMessage.To); //异步发送 (异步发送时页面上要加上Async="true" )
    }

/// <summary>
    /// 发送邮件的方法(发送多个收件人)只有橙色的部分有区别
    /// </summary>
    /// <param name="toMails">目的邮件地址</param>
    /// <param name="title">发送邮件的标题</param>
    /// <param name="content">发送邮件的内容</param>
    public void SendMail(string[] toMails,string title, string content)
    {
         //收件人邮箱地址
        if (toMails.Length>0)
        {
            for (int i = 0; i < toMails.Length; i++)
            {
                mailMessage.To.Add(toMails[i]);
            }
        }

        //邮件标题编码
        mailMessage.SubjectEncoding = Encoding.UTF8;
        //邮件主题
        mailMessage.Subject = title;
        //邮件内容
        mailMessage.Body = content;
        //邮件内容编码
        mailMessage.BodyEncoding = Encoding.UTF8;
        //设置正文内容是否是包含Html的格式
        mailMessage.IsBodyHtml = true ;
        //发送邮件的优先等级(有效值为High,Low,Normal)
        mailMessage.Priority = MailPriority.Normal;
        client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
        //发送邮件
        //发送邮件
        //client.Send(mailMessage);   //同步发送
        client.SendAsync(mailMessage, mailMessage.To); //异步发送 (异步发送时页面上要加上Async="true" )
    }

方法2:这种方法的参数比较灵活

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;

/// <summary>
///发送邮件类
/// </summary>
public class SmtpMail
{
    private SmtpClient client;
    private MailMessage message;

    public SmtpMail()
    {
        message = new MailMessage();
        client = new SmtpClient();
        client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);

    }

    /// <summary>
    /// delegate 处理邮件发送
    /// </summary>
    public delegate void SendCompleteHandle(object sender, System.ComponentModel.AsyncCompletedEventArgs e);

    /// <summary>
    /// event 处理邮件发送完成后的事件
    /// </summary>
    public event SendCompleteHandle SendComplete;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="host">主机地址/域名</param>
    /// <param name="username">发送账户</param>
    /// <param name="password">发送密码</param>
    /// <param name="port">邮件发送端口</param>
    /// <param name="usedefaultcredentials">是否采用默认验证方式</param>
    public SmtpMail(string host, string username, string password, int port, bool usedefaultcredentials)
        : this()
    {
        client.UseDefaultCredentials = usedefaultcredentials;
        client.Credentials = new System.Net.NetworkCredential(username, password);
        client.Host = host;
        client.Port = port;
    }
    /// <summary>
    /// 发件人
    /// </summary>
    public string Form
    {
        get { return message.From.Address; }
        set
        {
            if (value == null || value == string.Empty) return;
            message.From = new MailAddress(value);
            message.ReplyTo = message.From;
        }
    }

    /// <summary>
    /// 主题
    /// </summary>
    public string Subject
    {
        get { return message.Subject; }
        set { message.Subject = value; }
    }

    /// <summary>
    /// 内容
    /// </summary>
    public string Body
    {
        get { return message.Body; }
        set { message.Body = value; }
    }

    /// <summary>
    /// 邮件格式。True:为html,false:为text
    /// </summary>
    public bool IsBodyHtml
    {
        get { return message.IsBodyHtml; }
        set { message.IsBodyHtml = value; }
    }


    /// <summary>
    /// 邮件标题编码
    /// </summary>
    public System.Text.Encoding SubjectEncoding
    {
        get { return message.SubjectEncoding; }
        set { message.SubjectEncoding = value; }
    }

    /// <summary>
    /// 邮件内容编码
    /// </summary>
    public System.Text.Encoding BodyEncoding
    {
        get { return message.BodyEncoding; }
        set { message.BodyEncoding = value; }
    }
    /// <summary>
    /// 发送邮件的优先等级
    /// </summary>
    public MailPriority Priority
    {
        get { return message.Priority; }
        set { message.Priority = value; }
    }

    public SmtpDeliveryMethod DeliveryMethod
    {
        get { return client.DeliveryMethod; }
        set { client.DeliveryMethod = value; }
    }
    /// <summary>
    /// 获取邮件是否可以发送
    /// </summary>
    /// <returns>返回true:邮件可以发送;false:邮件缺少发送的必要因素</returns>
    public bool CanSent
    {
        get
        {
            if (message.From == null || message.To.Count == 0)
                return false;
            else
                return true;
        }
    }

    private void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
        if (SendComplete == null) return;

        SendComplete(sender, e);
    }
    /// <summary>
    /// 添加收件人
    /// </summary>
    /// <param name="to">收件人地址</param>
    public void AddTo(params string[] to)
    {
        for (int i = 0; i < to.Length; i++)
        {
            message.To.Add(to[i]);
        }
    }


    /// <summary>
    /// 清空收件人
    /// </summary>
    public void ClearMessageTo()
    {
        message.To.Clear();
    }

    /// <summary>
    /// 发送
    /// </summary>
    /// <returns></returns>
    public void Send()
    {
        if (message.From == null || message.To.Count == 0)
        {
            throw new Exception("无效发件人或收件人!");
        }

        try
        {
            client.Send(message);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// 异步发送
    /// </summary>
    public void SendAsync()
    {
        if (message.From == null || message.To.Count == 0)
        {
            throw new Exception("无效发件人或收件人!");
        }

        try
        {
            client.SendAsync(message, message.To);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

可以在web.config加上方法1的配置

注意:若是异步发送邮件,要在页面上加Async="true"
在页面上调用以上两个方法之中的一个都可以进行同步或异步发送邮件

转载于:https://www.cnblogs.com/aijun/archive/2011/03/15/1984558.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值