【问题标题】:.Net send mail through Gmail [duplicate].Net通过Gmail发送邮件[重复]
【发布时间】:2012-04-13 10:56:13
【问题描述】:

可能重复:
Sending email in .NET through Gmail

我正在尝试通过我创建的 GMail 帐户使用 Asp.Net (MVC3) 发送邮件。我已经在互联网上抓取了操作方法,但我尝试过的任何方法都没有奏效。

我有一个看起来像这样的方法

public static bool SendEmail(string to,string subject,string body)
    {
        try
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("myaccount@gmail.com");
            mail.To.Add(to);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = false;

            SmtpClient smtp = new SmtpClient();
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.Credentials = new System.Net.NetworkCredential("myaccount@gmail.com", "mypassword");
            smtp.EnableSsl = true;
            smtp.Send(mail);
            return true;
        }
        catch
        {
            return false;
        }
    }

这个方法在我使用它时返回false。我该如何解决这个问题?

【问题讨论】:

  • 把catch换成catch(Exception e)然后放个断点看看是什么错误
  • 您的(和/或网络应用程序的)防火墙上是否打开了出站端口 587?
  • 你可以从不吞下异常开始。然后阅读重复问题的答案。

标签: c# asp.net-mvc-3


【解决方案1】:

我验证了以下作品:

static void Main(string[] args)
{
    //create the mail message
    MailMessage mail = new MailMessage();

    var client = new SmtpClient("smtp.gmail.com", 587)
    {
        Credentials = new NetworkCredential("your.email@gmail.com", "yourpassword"),
        EnableSsl = true
    };

    //set the addresses
    mail.From = new MailAddress("your.email@gmail.com");
    mail.To.Add("to@wherever.com");

    //set the content
    mail.Subject = "Test subject!";
    mail.Body = "<html><body>your content</body></html>";
    mail.IsBodyHtml = true;
    client.Send(mail);
}

【讨论】:

    【解决方案2】:

    尝试添加这一行

     smtp.UseDefaultCredentials = false;
    

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 2014-08-27
      • 1970-01-01
      • 2011-10-21
      • 2010-09-07
      • 2012-07-14
      相关资源
      最近更新 更多