在asp.net中发送电子邮件(Gmail)

时间:2013-03-21 21:45:51

标签: asp.net email smtp gmail email-integration

我试图在asp.net c#上使用email发送gmail account,但我一直收到此错误:

  

连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应[2607:f8b0:400c:c01 :: 6c]:587

我尝试过不同资源的不同代码,但没有一个代码适用于我的项目 更多的事情我尝试了这些步骤,但仍然没有工作:

  1. 在VS 2012服务器和localhost(iis 7)上尝试端口25,465,587。
  2. 防火墙设置为关闭,防病毒设置为关闭。
  3. 以管理员身份启动visual studio。
  4. 拜托,有谁能告诉我这个错误背后的原因是什么。如果有可能改变某些东西,我应该从哪里开始......

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    public partial class Default6 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var myMailMessage = new System.Net.Mail.MailMessage();
            myMailMessage.From = new System.Net.Mail.MailAddress("serveremail@gmail.com");
            myMailMessage.To.Add("youremail@yahoo.com");// Mail would be sent to this address
            myMailMessage.Subject = "Feedback Form";
            myMailMessage.Body = "Hello";
    
            var smtpServer = new System.Net.Mail.SmtpClient("smtp.gmail.com");
            smtpServer.Port =587;
            smtpServer.Credentials = new System.Net.NetworkCredential("serveremail@gmail.com", "**YOURPASSWORD**");
            smtpServer.EnableSsl = true;
            smtpServer.Send(MyMailMessage);
    
            Response.Redirect("Default.aspx");
        }
    }
    

2 个答案:

答案 0 :(得分:2)

试试这个,
添加命名空间

system.net; system.net.mail;

 protected void Button1_Click(object sender, EventArgs e)
    {
        MailMessage MyMailMessage = new MailMessage();

        MyMailMessage.From = new MailAddress("from");

        MyMailMessage.To.Add("to");

        MyMailMessage.Subject = "Feedback Form";

        MyMailMessage.Body = "This is the test message from xx for testing mail send";

        MyMailMessage.IsBodyHtml = true;

        SmtpClient SMTPServer = new SmtpClient("smtp.gmail.com");

        SMTPServer.Port = 587;

        SMTPServer.Credentials = new System.Net.NetworkCredential("username","password");

        SMTPServer.EnableSsl = true;

        try
        {

            SMTPServer.Send(MyMailMessage);

           //Response.Redirect("Thankyou.aspx");

        }

        catch (Exception ex)
        {



        }

答案 1 :(得分:0)

你可以试试这个:

 MailMessage mail = new MailMessage();
 mail.Subject = "Your Subject";
 mail.From = new MailAddress("senderMailAddress");
 mail.To.Add("ReceiverMailAddress");
 mail.Body = "Hello! your mail content goes here...";
 mail.IsBodyHtml = true;

 SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
 smtp.EnableSsl = true;
 NetworkCredential netCre = new NetworkCredential("SenderMailAddress","SenderPassword" );
 smtp.Credentials = netCre;

 try
  {
   smtp.Send(mail);                
  }
  catch (Exception ex)
  {        
  }