Pages

Mar 16, 2009

Sending Email using C# and ASP.Net 2.0

Sending a Simple Mail Using GMail SMTP SERVER :

Use the namespace

using
System.Web.Mail;

MailMessage mail = new MailMessage();

mail.To.Add("to@gmail.com");

mail.From = new MailAddress("from@gmail.com");

mail.Subject = "Test Email";

string Body = "Welcome to Mukund's Blog";

mail.Body = Body;

mail.IsBodyHtml = true;

SmtpClient smtp = new SmtpClient();

smtp.Host = ConfigurationManager.AppSettings["SMTP"];

smtp.Credentials = new

System.Net.NetworkCredential(ConfigurationManager.AppSettings["FROMEMAIL"],

ConfigurationManager.AppSettings["FROMPWD"]);

smtp.EnableSsl = true;

smtp.Send(mail);

The above code can be used to send a simple email.


Sending Mail with Attachment:

MailMessage mail = new MailMessage();

mail.To.Add("to@gmail.com");

mail.From = new MailAddress("From@gmail.com");

mail.Subject = "Test Email";

string Body = "Welcome to Mukund's Blog";

mail.Body = Body;

mail.Attachments.Add(new Attachment(@"F:\Articles\Email in ASP.Net 2.0\SendEmail\mail.png"));

SmtpClient smtp = new SmtpClient();

smtp.Host = ConfigurationManager.AppSettings["SMTP"];

smtp.Send(mail);


The webcongif file should contain the following code.

Add open triangle and close triangle braces for each tag.

appSettings

add key="SMTP" value="smtp.gmail.com"

add key="FROMEMAIL" value="mail@gmail.com"

add key="FROMPWD" value="password"

appSettings

The above code can be used to send a simple email with attachment.