c# - 我想通过 ASP.NET 发送邮件但发生错误
问题描述
我在此联系表单的后端使用 C#,而 html 是前端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class index : System.Web.UI.Page
{
protected void Send_Click(object sender, EventArgs e)
{
try
{
MailMessage message = new MailMessage(From.Text, To.Text, Subject.Text, Body.Text);
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com", 465);
client.EnableSsl = true;
// The credentials when I ran the code were correct.
client.Credentials = new System.Net.NetworkCredential("example@gmail.com","password");
client.Send(message);
status.Text = "Mail was sent successfully";
status.Text = "Send was clicked";
}
// This catch block is so that you can see what error
// occurs if there is an error
catch(Exception ex)
{
status.Text = ex.StackTrace;
}
}
}
这是显示的错误
System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode,字符串响应)
在 System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] 命令, MailAddress from, Boolean allowUnicode)
在 System.Net.Mail.SmtpTransport.SendMail(MailAddress 发件人, MailAddressCollection 收件人, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& 异常)
在 C:\Users\robert.crider\source\repos\WebSite2\WebSite2\index.aspx.cs 中 index.Send_Click(Object sender, EventArgs e) 处的 System.Net.Mail.SmtpClient.Send(MailMessage 消息):第 37 行
解决方案
确保您为 google smtp 和交付网络使用正确的端口。并且您已在 Gmail 帐户设置中启用IMAP 和/或 POP3 访问。
SmtpClient client= new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(yourgoogleemail, yourgooglepassword),
Timeout = 3000
};