问题描述
下面是我正在使用的代码。请在下面找到错误消息。请告知如何纠正此问题。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Net.Mail;
public partial class mailtest : System.Web.UI.Page
{
protected void Page_Load(object sender,EventArgs e)
{
}
protected void SendEmail(object sender,EventArgs e)
{
lblmsg.Text = "";
try
{
using (MailMessage mm = new MailMessage(txtEmail.Text,txtTo.Text))
{
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
//if (fuAttachment.HasFile)
//{
// string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
// mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream,FileName));
//}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = txtsmtphost.Text.Trim();
smtp.EnableSsl = false;
if (chkssl.Checked == true)
{
smtp.EnableSsl = true;
}
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text,txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(txtport.Text);
smtp.Send(mm);
lblmsg.ForeColor = System.Drawing.Color.DarkGreen;
lblmsg.Text = "Email sent successfuly !!";
//ClientScript.RegisterStartupScript(GetType(),"alert","alert('Email sent successfuly !!');",true);
}
}
catch (Exception ex)
{
lblmsg.ForeColor = System.Drawing.Color.Red;
lblmsg.Text = "Failed " + ex.ToString();
ClientScript.RegisterStartupScript(GetType(),"alert('Failed');",true);
}
}}
下面的错误信息
System.Net.Mail.SmtpException:SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为:5.7.0 Authentication required。了解更多信息,请访问 System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode,String response) at System.Net.Mail.MailCommand.Send(SmtpConnection conn,Byte[] command,MailAddress from,Boolean allowUnicode) at System.Net。 Mail.SmtpTransport.SendMail(MailAddress 发件人,MailAddressCollection 收件人,String deliveryNotify,Boolean allowUnicode,SmtpFailedRecipientException& 异常)在 System.Net.Mail.SmtpClient.Send(MailMessage message)
解决方法
您应该在用于发送电子邮件的 Gmail 帐户上启用 less secure app
设置。您可以使用此 Link 来启用设置。
有关您的问题的更多信息 here。
,SMTP 服务器需要安全连接或客户端未通过身份验证。
要解决此错误,请转到您的 Google 帐户并生成一个 apps password
运行代码时,使用生成的密码而不是实际用户密码。
当帐户启用了 2fa 时,这种情况最常发生。
SmtpClient 示例
using System;
using System.Net;
using System.Net.Mail;
namespace GmailSmtpConsoleApp
{
class Program
{
private const string To = "test@test.com";
private const string From = "test@test.com";
private const string GoogleAppPassword = "XXXXXXXX";
private const string Subject = "Test email";
private const string Body = "<h1>Hello</h1>";
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,Credentials = new NetworkCredential(From,GoogleAppPassword),EnableSsl = true,};
var mailMessage = new MailMessage
{
From = new MailAddress(From),Subject = Subject,Body = Body,IsBodyHtml = true,};
mailMessage.To.Add(To);
smtpClient.Send(mailMessage);
}
}
}