Tuesday, May 27, 2008

How to send mail in C# ?

Often a c# programmer has to write code to send e-mails. This feature is required in many scenarios such as sending a mail once a scheduled job is over or sending a mail after the daily builds are done etc. Here is a sample code that can be used to send emails using C#.


using System.Net.Mail;

namespace EmailHelper
{
public static class EMail
{
public static void SendMail()
{
// Create mail message object
MailMessage mail = new MailMessage();
// Add the FROM address
mail.From = new MailAddress("sender@mail.com");
// Add TO address
mail.To.Add(new MailAddress("me@mail.com"));
// Enter the subject
mail.Subject = "This is a test Mail.";
// Enter body of email
mail.Body = "This is the body of the test mail.";
// Put smtp server you will use
SmtpClient smtpServer = new SmtpClient("SMTP Host");
// Send the mail
smtpServer.Send(mail);
}
}
}

In the above code we make use of System.Net.Mail namespace. In the SendMail method, we first create a mail message using the MailMessage class and then send it using the SmtpClient. A SMTP server is specified which is used to send mails.

Comments are Welcome !

2 comments:

Kuldeep Chowhan said...

Good One!

ppcc said...

hi kuldeep,
I am using the same code for sending mail but i am getting an error saying "Failure mail send", i have check Host name is same as my Outlook mailbax setup.

Post a Comment