Tuesday, February 3, 2009

Sending email in C# using GMail!



Here is some code I put together to send email using your Gmail account.
This can come in handy if you want your app to send notifications and you don't have access to an SMTP server.

Remember there is a limit that Gmail puts on mass emails. They will punish you if you go over it.

Gmail Sending Limits
In an effort to fight spam and prevent abuse, Google will temporarily disable your account if you send a message to more than 500 recipients or if you send a large number of undeliverable messages. If you use a POP or IMAP client (Microsoft Outlook or Apple Mail, e.g.), you may only send a message to 100 people at a time. Your account should be re-enabled within 24 hours.



Remember to set "DeliveryMethod = SmtpDeliveryMethod.Network". If this is not set then Gmail will come back with a "client was not authenticated" error.

Code
using System.Net.Mail;
using System.Net;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@yahoo.com", "To Name");
const string fromPassword = "password";
const string subject = "test";
const string body = "Hey now!!";

var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}