I updated an application recently that use the .NET 3.5 version of the send mail. This has been working find with gmail for sending mail.
The problem is when I upgraded to .NET 4.0 it gave an obsolete message on the old send mail so I upgrade to the new SmtpClient.
Note the new SmtpClient is in many ways easier to use and gives better error message but needless to say it did not work with gmail, hum!
So after some fighting with the most obvious problem and seaching the net and gmail help I finally changed the port from 465 to 587 and majically it all started to work. I am not sure why the old send mail worked fine with 465 and the new one only works with 587 but that seems to be the case.
Below is the test code I was using.
class Program
{
static string UserId = "gmail user id";
static string UserPw = "gmail password";
static void Main(string[] args)
{
SendMail("<to email>", "<from email", "Test message", "testing testing testing");
}
static bool SendMail(string to, string from, string subject, string body)
{
var msg = new System.Net.Mail.MailMessage();
msg.To.Add(new System.Net.Mail.MailAddress(to));
msg.Subject = to;
msg.Body = from;
msg.From = new System.Net.Mail.MailAddress(from);
try
{
// 465 does not work
var client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(UserId, UserPw);
client.Send(msg);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return false;
}
}
first test
second test
third test