Monday, January 20, 2014

How to send mail using C# in ASP.NET

Mail sending is a vital thing in web technology. In ASP.NET you have to follow a very few steps to send a mail from your email id to others. So how to send mail using C# in ASP.NET. Lets have a look..

You need to take help of two new classes. 
and a namespace has to be imported. 
  • using System.Net.Mail;
So lets check the code here.

MailMessage mail = new MailMessage();
mail.To.Add(txtTo.Text.Trim());
mail.From = new MailAddress("<Your mail id>");
mail.Subject = txtSubjcet.Text.Trim();
mail.Body = txtBody.Text.Trim();
mail.IsBodyHtml = true;
 

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;smtp.Credentials = new System.Net.NetworkCredential("<Your mail id>", "<Your password>");
smtp.Port = 587;
 

smtp.Send(mail);

Here, I have shown how to send mail using your Gmail id, for your own mail id contact your vendor for the host name & port no. Or you can also use other free mail servers like Yahoo, Outlook or Hotmail.

For Yahoo : Host name will be smtp.mail.yahoo.com and port no will be same as Google 587
For Hotmail : Host name will be smtp.live.com and give the port no 25.
For Outlook : Replace the code with the code here.


Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg.Subject = "<Subject>";
oMsg.HTMLBody = "<Message Body>";
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients; Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("<To be sent>"); 
oRecip.Resolve(); 
oMsg.Send();

Hope you have enjoyed the code. If you have any type of queries you can mail be @ arkadeepde.0@gmail.com.

Download the full source code here.

0 comments:

Post a Comment

Follow by Email

Popular Posts

Pageviews