Pages

Wednesday, September 29, 2010

Send email from yahoo, gmail or your smtp server through asp.net

To send a email from asp.net you need to follow these steps...

We use System.Net.Mail namespace to send email. Without going into details, lets have a simple working code to send emails through asp.net via two most popular smtp mail servers.

Gmail:


try
{
MailMessage mail = new MailMessage(); //using System.Net.Mail namespace
mail.To.Add("xyz@yahoo.com"); //Enter reciever's email address
mail.From = new MailAddress("abc@gmail.com"); //Enter sender's email address
mail.Subject = "Testing mail...";
mail.Body = @"Lets-code ! Lets-code to make it simpler";
mail.IsBodyHtml = true; //Body of mail supports html tags
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("abc@gmail.com", "pwd");
// Your gmail username and password
smtp.EnableSsl = true; //Gmail uses a encrypted connection
smtp.Send(mail);
Response.Write("Mail Sent Successfully");
}

catch(Exception ex)
{
Response.Write(ex.Message);
}





Yahoo:

Yahoo's Smtp host name is smtp.mail.yahoo.com. It uses port 25 and an unsecure connection. So, considering these, here's a code for yahoo.


try
{
MailMessage mail = new MailMessage();
mail.To.Add("xyz@gmail.com");
mail.From = new MailAddress("abc@yahoo.com");
mail.Subject = "This is subject of your mail";
string Body = @"Its the body of your mail";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.mail.yahoo.com";
smtp.Port = 25;
smtp.Credentials = new System.Net.NetworkCredential("abc@yahoo.com","pwd");
// Your yahoo username and Password
smtp.EnableSsl = false; // SSL is disabled
smtp.Send(mail);
Response.Write("Mail Sent Successfully");
}

catch (Exception ex)
{
Response.Write(ex.Message);
}


Yahoo appends its advertisements in your mail. So its better to use gmail.


Here's a list of other smtp mail servers:

  • Hotmail Outgoing Mail Server (SMTP) - smtp.live.com (SSL enabled, port 25)

  • Yahoo Plus Outgoing Mail Server (SMTP) - plus.smtp.mail.yahoo.com (SSL enabled, port 465, use authentication)

  • MSN Outgoing Mail Server - smtp.email.msn.com (uses authentication)

  • Netscape Internet Service Outgoing Mail Server - smtp.isp.netscape.com (port 25, uses a secure SSL connection)

If you want to mail from your own smtp mail server, just change the respective host,port.Check if your mail server supports SSL connection and enable/disable it accordingly.


Blogger's Default Comment Box