我想通过ASP.NET发送邮件,但发生错误

时间:2018-12-31 02:27:11

标签: c# asp.net visual-studio smtp

此联系表单的后端使用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,布尔值allowUnicode)
  在System.Net.Mail.SmtpTransport.SendMail(MailAddress发件人,MailAddressCollection收件人,字符串deliveryNotify,布尔值allowUnicode,SmtpFailedRecipientException&异常)
  在System.Net.Mail.SmtpClient.Send(MailMessage消息)处位于C:\ Users \ robert.crider \ source \ repos \ WebSite2 \ WebSite2 \ index.aspx.cs:line中index.Send_Click(Object sender,EventArgs e)处37

1 个答案:

答案 0 :(得分:2)

请确保您为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
        };