Code snippet to send Email from C# code

by Hozefa 21. August 2012 06:48
using System.Net.Mail;

The System.Net.Mail class provides a simple interface to for the Email message and add recipients and sender information. This MailMessage is further passed in the Send method of the SMTP client.

private void btnSendEmail_Click(object sender, EventArgs e)
{
    try
    {
        MailMessage mail = new MailMessage();
        mail.To.Add("hozefam@live.in");
        mail.From = new MailAddress("hozefam@gmail.com", "Hozefa Mangalorewala");
        mail.Subject = "Email Demo from hozefam@gmail.com";
        mail.Body = "This is a demo from  <a href='http://www.hozefam.com'>Hozefam.com</a>";
        mail.IsBodyHtml = true;

        SmtpClient smtp = new SmtpClient("smtp.gmail.com");
        smtp.Credentials = new System.Net.NetworkCredential("YourEmail", "YourPassword");
        smtp.EnableSsl = true;
        smtp.Send(mail);

    }
    catch (Exception ex)
    {
        
        throw ex;
    }
}

Change YourEmail and YourPassword to your email and password and make the necessary changes to the email addresses in the MailMessage To and From collection. To add more mail recipents address add mail entry to the mail.To collection.

MailMessage mail = new MailMessage();
mail.To.Add("hozefam@live.in");
mail.To.Add("hozefam@gmail.com");
mail.To.Add(hozefam@hozefam.com);

If you get an error saying, "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

Add an entry to bypass the proxy in the web.config like below :

<system.net>
  <defaultProxy>
  <proxy proxyaddress="YourProxyIpAddress"/>
  </defaultProxy>
</system.net>

also it is advisable to add the port number in the SMTP client like below:

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;

 

Tags:

.NET

Comments (1) -

Dotty Corlett
Dotty Corlett United States
8/28/2012 12:03:07 PM #

Paki, aunque con retraso, te comunico que todos los que lo solicist teis a trav s de los coemntarios est is admitidos/as

Reply

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Me

Skills set includes - ASP.NET, C#, MVC3, JQuery, Javascript, HTML, AJAX and XML also hobbist programmer and geek to try out new innovations in Microsoft world.

Facebook - facebook.com/hozefam

Twitter - twitter.com/hozefam

Mail - hozefam@gmail.com

 

Month List

Page List