Sending email using gmail SMTP server using .NET

If you do not have an SMTP server of your own, you can still send SMTP authenticated emails from your .net application. Just sign up for a brand new gmail account or use your exisiting gmail account.

SmtpClient obj = new SmtpClient(“smtp.gmail.com”,465);
//465 is the TCP port for sending emails using gmail. 465 is generally used for SMTP with SSL.

obj.EnableSsl = true;
obj.Credentials=new System.Net.NetworkCredential(“username@gmail.com”, “password”);
// your email address and its password for the SMTP authentication

MailMessage Mailmsg = new MailMessage();
Mailmsg.To.Clear();
Mailmsg.From = new MailAddress(“username@gmail.com”);
Mailmsg.Subject = “Subject”;
Mailmsg.Body =”Body”;

//adding attachments
Attachment at = new Attachment(Server.MapPath(“~/document.doc”));
Mailmsg.Attachments.Add(at);
Mailmsg.Priority = MailPriority.High;
Mailmsg.IsBodyHtml = true;
Mailmsg.To.Add(new MailAddress(“mailaddress”, “name”));
Mailmsg.BodyEncoding = System.Text.Encoding.Default;
try
{

obj.Send(Mailmsg);

}
catch (Exception ex)
{

Response.Write(ex.Message.ToString());

}

Mayur Gondaliya - CTO - CaseTronyx, Inc. Director - ExaSpring Information Services Pvt. Ltd. Web Investor. Software Engineer. Workaholic. Insomniac.

Leave a Reply