.net发送邮件

首先在页面头部加入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();
    }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。