如何使用System.Net.Mail正确发送电子邮件

问题描述 投票:0回答:1

我在 Visual Studio 中使用 Windows 窗体工作。我做了一个方法SendVerificationCode,使用System.Net.Mail发送验证码:

using System.Net.Mail;

namespace PasswordManager
{
    public partial class Form1 : Form
    {
        Random rnd = new();
        private void SendVerificationCode(object sender, EventArgs e)
        {
            if (!(textBox4.Text == "") && !(textBox2.Text == ""))
            {
                verificationCode = "";
                for (int _ = 0; _ < 4; _++)
                {
                    verificationCode += nums[rnd.Next(0, 10)];
                }
                try
                {
                    MailMessage mail = new MailMessage();
                    SmtpClient smtp = new SmtpClient();

                    mail.From = new MailAddress("**********@gmail.com");
                    mail.To.Add(textBox2.Text);
                    mail.Subject = "Verification code";
                    mail.Body = verificationCode;

                    smtp.Host = "smtp.gmail.com";
                    smtp.Port = 587;
                    smtp.Credentials = new System.Net.NetworkCredential("*********@gmail.com", "**********");
                    smtp.EnableSsl = true;

                    smtp.Send(mail);
                }
                catch (Exception){ throw new Exception("its not working"); }
            }
        }
    }
}

textBox2.Text 是********@wp.pl。

它抛出异常(“它不起作用)

有人可以帮助我吗????

谢谢你。

c# winforms email system.net.mail
1个回答
0
投票

您正在尝试从 Gmail 地址发送。 Gmail 不再允许简单的用户名/密码身份验证。您需要获取 OAuth2 令牌...System.Net.Mail 不支持该令牌。

也就是说,您无法使用.NET 的内置 SMTP 客户端来执行此操作。

有第三方库可以提供帮助。 MailKit 就是一个例子。

© www.soinside.com 2019 - 2024. All rights reserved.