Monday, October 19, 2009

Sending email in asp.net 3.5

Sending email is a very important in web application for remind anything to user, newsletter ,invitation or reset password etc.In .Net 1.1 we used System.Web.Mail.SmtpMail for sending emails , which is now obsolete. Now in asp.net 2.0 or higher version we can use System.Net.Mail.Smtpmail to send mail.


Code for sending email in asp.net 3.5

SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress("from@site.com","Nameofsendingperson");
message.From = fromAddress; //here you can set address
message.To.Add("to@abc.com"); //here you can add multiple to
message.Subject = "Subject Goes Here"; //subject of email
message.Body =@"Body Text";
smtpClient.Send(message);
}
catch (Exception ex)
{
//throw exception here you can write code to handle exception here
}


For adding attachment with your mail you need to write following code

message.Attachments.Add(New System.Net.Mail.Attachment(Filename))

Here Filename will be the physical path along with the file name. You can attach multiple files with the mail.


If you want to sent a email with authentication then you have to write following code.

System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient();
//This object stores the authentication values
System.Net.NetworkCredential basicCrenntial =
new System.Net.NetworkCredential("username", "password");
mailClient.Host = "Host";
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = basicCrenntial;
mailClient.Send(message);

No comments: