0

Possible Duplicate:
Sending email in .NET through Gmail

I am trying to send a mail with Asp.Net (MVC3) through an GMail-account i've created. I've crawled the internet for how-to's, but nothing i tried has been working.

I have a method that looks like this

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

This method returns false when im using it. How can i solve this?

Community
  • 1
  • 1
Anton Gildebrand
  • 3,641
  • 12
  • 50
  • 86

2 Answers2

2

I verified the following works:

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);
}
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
0

Try Adding this line

 smtp.UseDefaultCredentials = false;
Apurv Gupta
  • 870
  • 7
  • 14