gpt4 book ai didi

c# - 如何使用 C# 通过 Gmail 发送电子邮件

转载 作者:可可西里 更新时间:2023-11-01 08:15:41 25 4
gpt4 key购买 nike

尝试通过网络服务发送电子邮件时出现错误。我尝试启用对安全性较低的应用程序的访问,禁用两步验证并通过网络浏览器登录帐户。 SO 上的所有解决方案都不适合我。我仍然得到:

Error: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

我该怎么做才能解决这个问题?

namespace EmailService
{
public class Service1 : IService1
{
public string SendEmail(string inputEmail, string subject, string body)
{
string returnString = "";
try
{
MailMessage email = new MailMessage();
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";

// set up the Gmail server
smtp.EnableSsl = true;
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("myemail@gmail.com", "mypassword");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;

// draft the email
MailAddress fromAddress = new MailAddress("cse445emailservice@gmail.com");
email.From = fromAddress;
email.To.Add(inputEmail);
email.Subject = body;
email.Body = body;

smtp.Send(email);

returnString = "Success! Please check your e-mail.";
}
catch(Exception ex)
{
returnString = "Error: " + ex.ToString();
}
return returnString;
}
}
}

最佳答案

就到这里:Less secure apps , 使用您在 c# 代码中用于发送邮件的电子邮件和密码登录,然后选择 Turn On

另请转到此链接并单击继续 Allow access to your Google account

我也稍微编辑了一下:

public string sendit(string ReciverMail)
{
MailMessage msg = new MailMessage();

msg.From = new MailAddress("YourMail@gmail.com");
msg.To.Add(ReciverMail);
msg.Subject = "Hello world! " + DateTime.Now.ToString();
msg.Body = "hi to you ... :)";
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential("YourMail@gmail.com", "YourPassword");
client.Timeout = 20000;
try
{
client.Send(msg);
return "Mail has been successfully sent!";
}
catch (Exception ex)
{
return "Fail Has error" + ex.Message;
}
finally
{
msg.Dispose();
}
}

如果上面的代码不行,试试改成下面的代码:

    SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("YourMail@gmail.com", "YourPassword");

关于c# - 如何使用 C# 通过 Gmail 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29465096/

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