Search This Blog

Tuesday, October 19, 2010

Sending Email using C# and ASP.Net

Most often, we will have requirements to send email from our asp.net applications. This article will help us understand some of the available techniques we can use to send email from asp.net applications. With the introduction of .Netframework 2.0, the classes for sending email are packed in System.Net.Mail namespace as opposed to System.Web.Mail namespace in 1.x framework. Moving forward we will see,

Ø       Sending a Simple Mail
Ø       Sending Mail with Attachment
Ø       Sending Mail with HTML body
Ø       Sending Email with Embedded Image in the Message Body
Ø       Sending Email with Gmail SMTP Server from ASP.Net

Sending a Simple Mail
MailMessage mail = new MailMessage();
mail.To.Add("to@gmail.com");
mail.From = new MailAddress("from@gmail.com");
mail.Subject = "Test Email";
string Body = "Welcome to Mysite.Com!!";
mail.Body = Body;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com" ;
smtp.Send(mail);

Sending Mail with Attachment
We can also send email with attachments. The below code will help you to achieve it.

MailMessage mail = new MailMessage();
mail.To.Add("to@gmail.com");
mail.From = new MailAddress("From@gmail.com");
mail.Subject = "Test Email";
string Body = "Welcome to Mysite.Com!!";
mail.Body = Body;
mail.Attachments.Add(new Attachment(@"F:\Articles\Email in ASP.Net 2.0\SendEmail\mail.png"));
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com" ;
smtp.Send(mail);

Sending Mail with HTML Body
Sometimes, we will have requirements to send email as a HTML body. The below code will help you to achieve the same.
MailMessage mail = new MailMessage();
mail.To.Add("to@gmail.com");
mail.From = new MailAddress("From@gmail.com");
mail.Subject = "Test Email";
string Body = "Welcome to Mysite.com!!";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host ="smtp.gmail.com" ;
smtp.Send(mail);


Sending Email with Gmail SMTP Server from ASP.Net
To send email using gmail SMTP server you will require a valid gmail userid and password. If you didn’t specify a valid gmail userid and password then you will get the following error.

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

The below code can be used to send email using gmail SMTP server, smtp.gmail.com.

MailMessage mail = new MailMessage();
mail.To.Add("to@gmail.com");
mail.From = new MailAddress("from@gmail.com");
mail.Subject = "Test Email";
string Body = "Welcome to Mysite.com!!";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host ="smtp.gmail.com" ;
smtp.Credentials = new System.Net.NetworkCredential("mail@gmail.com","password");
smtp.EnableSsl = true;   
smtp.Send(mail);

No comments:

Post a Comment