码迷,mamicode.com
首页 > Web开发 > 详细

.net发送邮件

时间:2015-04-24 15:59:54      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

首先在页面头部加入Async="true"


后台代码中引入:
using System.Net;
using System.Net.Mail;
using System.Text;

public void SendMail(string addrto, string mailbody)
    {
        string addrfrom = "******@qq.com";//邮箱id
        string pwdfrom = "****";//邮箱密码
        //设置smtp服务器信息
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.Host = "smtp.qq.com";//指定SMTP服务名  例如QQ邮箱为 smtp.qq.com 新浪cn邮箱为 smtp.sina.cn等
        smtpClient.Port = 25; //指定端口号


        //创建服务器认证
        NetworkCredential networkCredential_my = new NetworkCredential(addrfrom, pwdfrom);
        //实例化发件人地址
        MailAddress mailAddress_from = new MailAddress(addrfrom, "*******");
        //指定发件人信息  包括邮箱地址和邮箱密码
        smtpClient.Credentials = new NetworkCredential(mailAddress_from.Address, pwdfrom);

        MailAddress mailAddress_to = new MailAddress(addrto);

        MailMessage mailmsg = new MailMessage(mailAddress_from, mailAddress_to);

        mailmsg.To.Clear(); //清空历史发送信息 以防发送时收件人收到的错误信息(收件人列表会不断重复)
        mailmsg.From = mailAddress_from;//发件人邮箱
        mailmsg.To.Add(mailAddress_to);//添加收件人邮箱地址
        //邮件主题
        mailmsg.Subject = "密码";
        mailmsg.SubjectEncoding = Encoding.UTF8;
        //邮件正文
        mailmsg.Body = mailbody;
        mailmsg.BodyEncoding = Encoding.UTF8;

        smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);//注册邮件发送完毕后的处理事件
        object userState = mailmsg;

        smtpClient.SendAsync(mailmsg, userState);
    }

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


        ShowMessage("发送成功!");
        ConfirmBttn.Enabled = true;
        try
        {
            if (e.Cancelled)
            {
                ShowMessage("发送取消");
            }
            if (e.Error == null)
            {
                ShowMessage("密码已发送至您的注册邮箱");
               
            }
            else
            {
                ShowMessage("发送失败" + e.Error.Message);
            }
        }
        catch
        {

        }
        //throw new NotImplementedException();
    }

.net发送邮件

标签:

原文地址:http://www.cnblogs.com/tomtang/p/4453437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!