Thursday, 24 March 2011

Sending email in asp.net 3.5 / 2.0

System.Net.Mail.Smtpmail For any web application or website the sending email is a necessity for newsletter, invitation or reset password for everything we have to sent a mail to the people. So we need to see how we can send mail. In 1.1 we are sending emails with System.Web.Mail.SmtpMail which is now obsolete. Now in asp.net 2.0 or higher version there is a namespace called System.Net.Mail.Smtpmail in asp.net 3.5. With this namespace we can easily write a code to send mail within couple of minutes.
If you want to sent a mail first thing you need is smtpserver. Smtpserver is a server which will route and send mail to particular system. To use smtpserver we need to configure some settings in web.config following is the setting for the web.config.
<system.net>
<mailsettings>
<smtp deliveryMethod="Network">
<network host="stmp server address or ip"
port="Smtp port" defaultCredentials="true"/>
</smtp>
</mailsettings>
</system.net>
Here you need to set the all the smtp configuration. This will be used by the smptclient by default. Here is the 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@site.com");//here you can add multiple to
message.Subject = "Feedback";//subject of email
message.CC.Add("cc@site.com");//ccing the same email to other email address
message.Bcc.Add(new MailAddress("bcc@site.com"));//here you can add bcc address
message.IsBodyHtml = false;//To determine email body is html or not
message.Body =@"Plain or HTML Text";
smtpClient.Send(message);
}
catch (Exception ex)
{
//throw exception here you can write code to handle exception here
}
So from above simple code you can add send email to anybody
Adding Attachment to the email:
message.Attachments.Add(New System.Net.Mail.Attachment(Filename))Here file name will the physical path along with the file name. You can attach multiple files with the mail.
Sending email with Authentication:
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);
If you want to sent a email with authentication then you have to write following code.
If you want to attach some thing in the code then you need to write following code.

No comments:

Post a Comment