65.9K
CodeProject is changing. Read more.
Home

Sending SMTP mail from ASP.NET and codebehind as C#

Apr 5, 2006

1 min read

viewsIcon

126070

downloadIcon

470

Sends authenticated mail

Introduction

.NET namespace system.web.mail allows users to send smtp mails. SMTP server runs on port 25. Now a day's spam messages are coming a lot. So all leading smtp servers requires proper authentication to send mails. Some SMTP servers can send messages without authentication. But that messages will be delivered to bulk folder in recepients mail box.

System.Web.Mail

This namespace has a class called MailMessage. First we have to create an object for this mail message class.

MailMessage mail = new MailMessage()

Mailmessage has some properties to specify mail attributes. Users can specify From name, to name, subject, body and attachments etc...

mail.To = "friendname@websitename.com";
mail.From = "yourname@websitename.com";
mail.Subject = "Mail Subject";
mail.Body = "Mail Body";

Adding attachments

For adding attchments create an object for MailAttchment class.

MailAttachment att = new MailAttachment(filename). 

Then add this mail attachment object to MailMessage object. For that use mail.AddAttchment(att). Now the mail is ready to send. Before that we have to authenticate the SMTP server.

Authenticating SMTP server

All leading mail servers requires authentication to send mails successfully. For that the sender email address and password should be given to server. Server will validate the address and password. For this we use microsoft schemas. Use MailMessage class's fileds property to add schemas.

mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 25;
mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"]  = 2;
mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = "yourname@websitename.com";
mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "yourpassword";
mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"]= "true";
this will send user name and password to server and you will be logged on to the server.

Finishing Up !!!

Next step is specifying the SMTP server you are going to use and sending the mail using MailMessageObject.Send property.

SmtpMail.SmtpServer = "smtp.gmail.com";  
SmtpMail.Send( mail );

Speed of mail delivery depends on bandwidth,size of attached file and speed of smtp server. I tried this on Gmail and got very good performance.


Happy programming
Cheers