C# 利用SMTP异步发送邮件

C#实现收发邮件功能需要用到两个命名空间  System.Net; 和 System.Net.Mail;

SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //发件服务器地址
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential("admin@meyer-mzq.com", "******");
client.EnableSsl = true;
client.Timeout = 15000;
client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted); //异步发送邮件完成响应事件

MailMessage mmsg = new MailMessage();
mmsg.From = new MailAddress("admin@meyer-mzq.com"); //发件人邮箱地址
mmsg.To.Add("admin@meyer-mzq.com"); //收件人邮箱地址

mmsg.Subject = "最新订单数据";      //邮件主题
mmsg.SubjectEncoding = Encoding.UTF8;   //主题编码
mmsg.Body = msg;  //邮件正文
mmsg.IsBodyHtml = true;    //设置为HTML格式  
mmsg.BodyEncoding = Encoding.UTF8;      //正文编码
mmsg.Priority = MailPriority.High;   //优先级
mmsg.Attachments.Add(new Attachment(file));//增加附件

try
{
    client.SendAsync(mmsg, ""); //异步发送邮件
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

由于采用异步发送邮件,需要添加一个异步完成时响应事件 client_SendCompleted

private void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
    if (e.Error != null)
    {
        MessageBox.Show("邮件发送失败,详情:" + e.Error.Message);
    }
    else
    {
        MessageBox.Show("邮件发送成功!");
    }
}
posted @ 2014-07-17 15:09  Tracine0513  阅读(940)  评论(0编辑  收藏  举报