在ASP.net中使用MimeKit,发送邮件

 public String GetAccountActivationCode()
        {
            int n = 6;
            StringBuilder code = new StringBuilder();
            Random ran = new Random();
            for (int i = 0; i < n; i++)
            {
                code.Append(ran.Next(9).ToString());
            }
            return code.ToString();
        }


   public String SendEmail()

        {
            string mailTo = "[email protected]";
            var message = new MimeMessage(); //设置消息对象
            string mailFromAccount = "[email protected]";
            string mailPassword = "tprnifnjzlhgcaib";  //这是在邮箱中开通smtp服务后的密码,在开通smtp服务的时候会发给你
            string mailFrom = "[email protected]";
           
            //添加from and to的消息地址列表和添加的地址
            message.From.Add(new MailboxAddress("gg", mailFrom));
            message.To.Add(new MailboxAddress("xx", mailTo ));   //前边的名字随便写,
            //设置消息主题
            message.Subject = "Account Activation Code:";
            //生成6位的验证码
            string code = GetAccountActivationCode();


            //创建消息的文本
            message.Body = new TextPart("plain")
            {
                Text = @code
            };


            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Connect("smtp.qq.com", 587, false); //前边是smtp的服务器,端口号
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(mailFromAccount, mailPassword);//认证发送者
                client.Send(message);//发消息
                client.Disconnect(true);


            }
            return code;
        }

猜你喜欢

转载自blog.csdn.net/u010565765/article/details/79450149