Friday, 13 April 2012

Send mail using ASP.NET with C#




Introduction

This tip describes how to send email using ASP.NET with C# and using a GMail or Yahoo! port.

Background

This code uses the System.Net.Mail namespace.

Using the code

Here is the complete code:
//send mail using gmail id
string ToAddress = TextBox3.Text;
const string FromAddress = "your gmail id";//For Example:rraanammeett@gmail.com
string Subject = TextBox6.Text;
String Body = TextBox4.Text;
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(ToAddress);
mail.From = new MailAddress(FromAddress);
mail.Subject = Subject;
mail.Body = Body;
mail.Priority = System.Net.Mail.MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential(FromAddress, "gmail id password");
client.Port = 587; // Gmail works on this port
client.Host = "smtp.gmail.com";client.EnableSsl = true; //Gmail works on Server Secured Layer
try
{
client.Send(mail);
}
catch (Exception error)
{
throw error;
} 

//send mail using yahoo id
string ToAddress = txtto.Text;
const string FromAddress = <a href="mailto:YourYahooId@yahoo.com">YourYahooId</a>;  //For Example <a href="mailto:rraanammeett@yahoo.comstring">rraanammeett@yahoo.com

string</a> Subject = txtsub.Text;
String Body = txtbody.Text;
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(ToAddress);
mail.From = new MailAddress(FromAddress);
mail.Subject = Subject;
mail.Body = Body;
            
mail.Priority = System.Net.Mail.MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("<a href="mailto:YourYahooId@yahoo.com">YourYahooId</a>", "Password");
client.Port = 587; 
client.Host = "smtp.mail.yahoo.com";
client.Send(mail);

No comments:

Post a Comment