Friday, March 25, 2011

Using Gmail Account to Send Emails

Sending Email using Gmail Account from your Application

The following piece of code will let you send email using Google server. Just replace network credentials with your Google user name and password.


private void button_send_Click(object sender, EventArgs e)
{
//Detailed Method

MailAddress mailfrom = new MailAddress("sender@gmail.com");
MailAddress mailto = new MailAddress("receiver@abc.com");
MailMessage newmsg = new MailMessage(mailfrom, mailto);

newmsg.Subject = "Subject of Email";
newmsg.Body = "Body(message) of email";

//For File Attachment, more file can also be attached
Attachment att = new Attachment("C:\\...file path");
newmsg.Attachments.Add(att);

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("username","password");
smtp.EnableSsl = true;
smtp.Send(newmsg);

//Alternative Short Method

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("username","password");
smtp.EnableSsl = true;
smtp.Send("sender@gamil.com", "receiver", "subject", "Email Body");
}


Note: Before providing credentials, you need to set UserDefaultCredentials to false.

The above mentioned settings are for Gmail, but you can also use other SMTP servers.

Have a nice time.

No comments: