gpt4 book ai didi

C#通过Gmail账户发送邮件

转载 作者:行者123 更新时间:2023-12-05 02:11:18 26 4
gpt4 key购买 nike

我正在使用简单的 CMD“服务”扩展我的 Web 应用程序,它应该向新注册的用户发送验证电子邮件。我的问题是通过验证 Gmail 帐户,抛出以下异常:

“SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为:5.5.1 需要身份验证。”

我已经尝试在我自己的 IMAP 服务器上进行身份验证,但也没有成功。后来我尝试使用XAMP Mercury邮件服务器,这不是最好的解决方案,由于完全依赖本地配置,所以我放弃了那个想法。将来,我只想为应用程序创建一个新的谷歌帐户,因此不需要维护。

  String body = "<head>" +
"Here comes some logo" +
"</head>" +
"<body>" +
"<h1>Account confirmation reqest.</h1>" + Environment.NewLine +
"<a>Dear User, </a>" + Environment.NewLine +
"<a>In order to be able to use musicshop app properly, we require You to confirm Your email address.</a>" + Environment.NewLine +
"<a>This is the last step towards using our app.</a>" + Environment.NewLine +
"<a>Pleas follow this hyperlink to confirm your address.</a>" + Environment.NewLine +
"<a>[Callback url]</a>" +
"</body>";
try
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential()
{
UserName = "myemail@gmail.com",
Password = "mypassword"
};
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
smtpClient.Send("targetemail@targetdomain.xyz", "myemail@gmail.com", "Account verification", body);
}
catch (Exception ex)
{
}

我只想能够通过 Gmail 服务器发送电子邮件,没有任何异常(exception)。我是否需要为此使用任何 NuGet 包,使用不同的方法?

最佳答案

如果您的 Gmail 帐户启用了两步验证,您将必须创建一个 App-Specific Password代替进行身份验证。

另请注意,SmtpClient 是 IDisposable - 您应该将其放入 using (var smtpClient = new SmtpClient("smtp.gmail.com", 587)) { ... 阻止 SMTP 连接 RSET、QUIT 和正确关闭。

== 编辑 ==

此外,您似乎在 smtpClient.Send 上切换了 fromrecipients 参数。

string body = "<head>" +
"Here comes some logo" +
"</head>" +
"<body>" +
"<h1>Account confirmation reqest.</h1>" + Environment.NewLine +
"<a>Dear User, </a>" + Environment.NewLine +
"<a>In order to be able to use musicshop app properly, we require You to confirm Your email address.</a>" + Environment.NewLine +
"<a>This is the last step towards using our app.</a>" + Environment.NewLine +
"<a>Pleas follow this hyperlink to confirm your address.</a>" + Environment.NewLine +
"<a>[Callback url]</a>" +
"</body>";
try
{
using (var smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential()
{
UserName = Config.Username,
Password = Config.Password,
};
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;

//Oops: from/recipients switched around here...
//smtpClient.Send("targetemail@targetdomain.xyz", "myemail@gmail.com", "Account verification", body);
smtpClient.Send("myemail@gmail.com", "targetemail@targetdomain.xyz", "Account verification", body);
}
}
catch (Exception e)
{
Console.Error.WriteLine("{0}: {1}", e.ToString(), e.Message);
}

关于C#通过Gmail账户发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57644814/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com