.Net通过Gmail发送邮件

时间:2012-03-29 18:38:01

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

  

可能重复:
  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。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

我验证了以下作品:

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);
}

答案 1 :(得分:0)

尝试添加此行

 smtp.UseDefaultCredentials = false;