Saturday, May 29, 2010

Send Email using SMTP Server

The .NET Framework includes the System.Net.Mail namespace, whcich provides classes to create and send email messages.Messages can include plain text,HTML and attachments

Creating & Send an email

Here We will create a class called email and we will implement the method called SendEmail inside the class.

Here the implemented class

***********************************************************
Remember you should add namespace "System.Net.Mail" first
***********************************************************

public class email
{
public int SendEmail()
{
try
{
//Create a MailMessage object
MailMessage mail = new MailMessage();

//To specify sender email address and Sender name
mail.From = new MailAddress("sender Email address", "Sender name");

//To specify recipient email address and recipient name
mail.To.Add(new MailAddress("recipient email address", "recipient name"));

//Set email Subject
mail.Subject = "Sample Email";

//Specify as HTML message body
mail.Body ="This is my message body";

//To Enable HTML body->You can type your message body using html tag.But blogger not support to post html tag in here.To enable HTML body you can use following code line.
//mail.IsBodyHtml = true;

//Attach files
mail.Attachments.Add(new Attachment(@"D:\oracle_database_11g.pdf"));


//Create a SmtpClient object
SmtpClient client = new SmtpClient();

//Assign a host for the client
client.Host = "smtp.gmail.com";

//Assign a port
client.Port=587;

//Give Credential information->Username and Password
client.Credentials=new System.Net.NetworkCredential("Your Username","Your Password");

//To enable SSL
client.EnableSsl=true;

//Send the mail
client.Send(mail);

return 1;
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
return 0;
}
}


}

No comments: