Microsoft.NET framework provides many rich class libraries which makes the life of developer easy. Sending emails could not be more simpler than which, is provided in Asp.net. In this article we will see how we can make use of the MailMessage class to send emails with attachments.


Introduction:

Microsoft.NET framework provides many rich class libraries which makes the life of developer easy. Sending emails could not be more simpler than which, is provided in Asp.net. In this article we will see how we can make use of the MailMessage class to send emails with attachments.

Developing the User Interface for our application: 

Below is a picture of what the user interface will look like. As you noted that there is a file field control which allows you to attach any file as a mail attachment. There is also a listbox which shows the files that are currently attached with the mail.

 

You can develop the same interface in any fashion you want. I just developed this since this seems simple.

Code for sending email:

Lets see the code to send an email. This code is executed on the button click control. First of all don't forget to add the

using System.Web.Mail;

namespace which provides the methods and properties for sending an email.

private void Button1_Click(object sender, System.EventArgs e)

{

MailMessage mail = new MailMessage();

mail.To = txtTo.Text;

mail.From = txtFrom.Text;

mail.Subject = txtSubject.Text;

mail.Body = txtBody.Text;

SmtpMail.SmtpServer = "localhost";

SmtpMail.Send(mail);

}

The code you see above is very simple to understand. In the button click event we made the object/instance of the MailMessage class. MailMessage is responsible for sending emails. It also provides several properties and methods. later we assigned several properties.

The line SmtpMail.SmtpServer = "localhost" sets the server for the mail. If you are running the application on your own pc using IIS than your server will be "localhost". If your website is running on the production server you can have different SmtpServer name.

The final line SmtpMail.Send(mail) sends the email to the email address provided. Until now we have not done any coding for the attachments. Lets see how this can be done.

Lets first examine the code for the attach button click event:

// Button used to attach a file private void Button2_Click(object sender, System.EventArgs e)

{

// gets the file name with the whole path

string attachedFile = File1.PostedFile.FileName;

 

// Adds the item in the list of attached files

if (attachedFile != "")

{

FileList.Items.Add(attachedFile);

}

}

In this code first we retrieve the whole path of the file from the file field object and assigns it to the attachedFile variable. Next we add the path of the file in our listbox if the path is not null meaning the path is only added when the user attaches a file. After the list is populated with the attachments it will look something like this:

As you see that adding the filename in the listbox control is pretty straightforward and simple. Now lets see how we can do the attachments.

If you like to make a single attachment you can do this easily like this:

mail.Attachments.Add( new MailAttachment(@"C:\myFile.txt"));

As you see making a single attachment is very easy. But in this case we need to make multiple attachments. What we will do is that we will iterate through the listbox and attach every file which is represented by its file path. Lets see the code that can accomplish that.

MailAttachment attachment = null ;

 

try

{

// check to see if there are any attachments or not

if (FileList.Items.Count > 0)

{

 

foreach(ListItem l in FileList.Items)

{

// Attaches a new attachment contained in the List

Response.Write(l.Text);

attachment = new MailAttachment(l.Text);

mail.Attachments.Add(attachment);

}

 

}

 

//mail.Attachments.Add(attachment);

Response.Write("Number of attachments are"+mail.Attachments.Count);

 

SmtpMail.SmtpServer = "localhost";

SmtpMail.Send(mail);

}

catch (Exception ex)

{

Response.Write(ex.Message);

 

// Cacthes the exception here

}

Explanation of the Code:

1) First we initialize the MailAttachment object "attachment" to null.

2) Then, in the try-catch block we check that if the listbox has any items or not by using its count property. If the listbox is empty and you try to make an attachment from the listbox item you will get an error specifying that the attachment is invalid.

3) Next, we used the foreach loop to iterate through the listbox and in each iteration we attaches the path contained in the listbox to the MailAttachment.

4) Inside the foreach loop we also add attachments to our mail object.

5) If you are unsure that how many attachments you have in the mail object you can use the property

mail.Attachments.Count

to get the total number of attachments for the current mail object.

6) Until now all the attachments have been made and we just simply set the server name and send the email using the SmtpMail.Send() method.

Problems you might encounter while sending emails:

In Visual Studio.NET 2002 sending mail was the same as easy. There are various problems that you might encounter while sending email using Visual Studio.NET 2003. These problems encounter because of the Smtp mail server settings. If you are using your production server for sending emails these problems are not likely to arise but, they do when you use "localhost" to send emails.

Always put a try catch block when sending emails. And also view the inner exception if the exception occurs. When sending email you might get "Could not access CDO message object". This is by far the most annoying error that you will see when sending emails.

There are many scenarios under which this error takes place. Let me explain few ways to resolve the problem.

1) Go to Control Panel -> Administrative tools -> IIS

2) Right Click on the Smtp Server which is at the bottom and select properties.

3) Select the Access Tab

4) Select the Relay option

5) Check the radio button which says use only listed below and add your localhost address to it which is "127.0.0.1".

6) Restart the IIS again and check that if the mail is being sent

If you are still facing problems please visit http://www.systemwebmail.com/ , this website is devoted to the errors that developers face when sending email using Asp.net.

Conclusion:

As you see in the article that emailing in Asp.net is fairly simple apart from some of the silly errors :). Its always a good idea to save coding and time and develop an email component which can be dragged and dropped on the form and used instantly. Microsoft Visual Studio.NET 2005 which will be released in December 2005 might have an email component already build in so we will not have to write 4-5 lines of code.