如何使用Gmail在ASP.NET中发送电子邮件?

时间:2014-02-06 14:40:11

标签: c# asp.net

我正在尝试使用我的网页发送电子邮件。 我正在使用我的Gmail ID。 我收到了错误:

 A connection attempt failed because the connected party did not properly respond after
 a period of time, or established connection failed because connected host has failed to
 respond 74.125.129.109:25

这是我的c#代码

    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;
    namespace sendmail
    {
      public partial class _Default : System.Web.UI.Page
      {
      protected void Page_Load(object sender, EventArgs e)
      {
      }
      protected void btnSubmit_Click(object sender, EventArgs e)     
      {     
       MailMessage Msg = new MailMessage();     
       Msg.From = new MailAddress("email@gmail.com");     
       Msg.To.Add(txtToMail.Text);     
       Msg.Subject = txtSubject.Text;     
       Msg.Body = txtMessage.Text;     
       Msg.IsBodyHtml = true;         
       SmtpClient smtp = new SmtpClient();     
       smtp.Host = "smtp.gmail.com";     
       System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();     
       NetworkCred.UserName = "email@gmail.com";     
       NetworkCred.Password = "mypassword";     
       // smtp.Timeout = 10000;     
       smtp.DeliveryMethod = SmtpDeliveryMethod.Network;    
       smtp.UseDefaultCredentials = false;     
       smtp.Credentials = NetworkCred;     
       smtp.Port = 25;     
       smtp.EnableSsl = false;     
       smtp.Send(Msg);
       lblMsg.Text = "Email has been successfully sent..!!";       
     }    
   }

} 

1 个答案:

答案 0 :(得分:0)

   public void MailSend()
    {
        using (MailMessage mailMessage = new MailMessage())
        {
            mailMessage.From = new MailAddress("mail@gmail.com");
            mailMessage.Subject = "subject";
            mailMessage.Body = "body";
            mailMessage.IsBodyHtml = true;
            mailMessage.To.Add(new MailAddress(mail));


            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
            NetworkCred.UserName = mailMessage.From.Address;
            NetworkCred.Password = "password";
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mailMessage);
        }
    }