5,693,062 members and growing! (18,220 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Intermediate

ASP.NET email with multiple attachments

By Luc Archambault

A simple web form that lets the user upload multiple attachments to create and send email.
C#, Windows, .NET 1.0, .NET, Visual Studio, ASP.NET, Dev

Posted: 11 Oct 2004
Updated: 25 Jan 2005
Views: 116,864
Bookmarked: 55 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
27 votes for this Article.
Popularity: 5.59 Rating: 3.90 out of 5
2 votes, 7.4%
1
0 votes, 0.0%
2
5 votes, 18.5%
3
7 votes, 25.9%
4
13 votes, 48.1%
5

Introduction

This application demonstrates the use of some simple but useful things you can do with ASP.NET; uploading, saving and deleting files, and sending email.

Background

There are three things we need to do to be able to run this code and I'm going to assume that you will be trying out this code at home on a Windows desktop computer.

First, you need to create a virtual directory in IIS to host this web application and set write permission because we will be saving and deleting files that will be email attachments. In the virtual directory, create a folder called "attachments". This is where we will temporarily store the uploaded files to attach to the email.

The second thing to do is to make sure that the SMTP server is running and that it can relay mail. From the IIS MMC window, with "local computer" selected on the left, you should see the "Default SMTP Virtual Server", if not you need to install it. Right-click it, go into "Properties", the "Access" tab, and click the "Relay" button. With the "only the list below" radio button selected, you should see the local IP address: 127.0.0.1, if it's not there, you need to add it.

The last thing is to set up the SMTP server in the application. In the code, look for this line (line # 149):

SmtpMail.SmtpServer = "localhost";

You need to replace "localhost" with the name or IP address of your SMTP mail server. On a Windows desktop computer, "localhost" is the default value and usually works.

Using the code

First of all, we create a new MailMessage object and we call it "email". Then we set the From, To, Subject and Body properties as well as the BodyFormatof of this object to the values on our web form.

// Create a new blank MailMessage

 MailMessage email = new MailMessage ();

// Set the properties of the MailMessage to the

// values on the form

 if (rblMailFormat.SelectedItem.Text == "text")
  email.BodyFormat = MailFormat.Text;
 else
  email.BodyFormat = MailFormat.Html;
 email.From = txtSender.Text;
 email.To = txtReceiver.Text;
 email.Subject = txtSubject.Text;
 email.Body = txtBody.Text;

Now for the meat and potatoes of this little web application; the following block of code checks the first of three Open File Dialogs of our web form (the Open File Dialog is an HTML File Field control to which we've added the runat="server" property). If there is a value, the file is uploaded, saved on the server, and added as an attachment to the email. The processing of the two other Open File Dialogs are just the same.

// Beginning of attachments processing

// Check the first open file dialog for a value

 if (ofdAttachment1.PostedFile != null)
 {
  // Get a reference to PostedFile object

  HttpPostedFile ulFile = ofdAttachment1.PostedFile;
  // Get size of the file

  int nFileLen = ulFile.ContentLength; 
  // Make sure the size of the file is > 0

  if( nFileLen > 0 )
  {
   // Get the file name

   strFileName = Path.GetFileName(ofdAttachment1.PostedFile.FileName);
   // Preced the file name with "attachments/" so 

   // the file is saved to our attachments directory

   strFileName = "attachments/" + strFileName;
   // Save the file on the server

   ofdAttachment1.PostedFile.SaveAs(Server.MapPath(strFileName));
   // Create the email attachment with the uploaded file

   MailAttachment attach = new MailAttachment(Server.MapPath(strFileName));
   // Attach the newly created email attachment

   email.Attachments.Add(attach);
   // Store filename so we can delete it later

   attach1 = strFileName;
  }
 }

Then we send the email and finish by deleting the attachments.

// Set the SMTP server and send the email

 SmtpMail.SmtpServer = "localhost";
 SmtpMail.Send (email);

// Delete the attachements if any

 if (attach1 != null)
  File.Delete(Server.MapPath(attach1));

Points of Interest

This little project shows a practical use of the System.Web.HttpPostedFile and the System.Web.Mail.SmtpMail objects. The HttpPostedFile object is probably the simplest way to let a web user upload a file. I also tried to create the file attachment using a FileStream, hoping that I would be able to create the attachment without having to first save the file. I haven't figured that one out yet.

History

I've made a minor update to this article and the code, but it's basically the same application. Someone pointed out that I hadn't included the line that adds "attachments/" to the beginning of the filename for the second and third attachments. That's the only thing that has changed in the code. I've also made a few small changes to my explanations and comments.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Luc Archambault


I have been working with different web technologies (ASP, ASP.NET, ColdFusion, Perl/CGI) for the past 7 years. I live in Montreal, where I work for a little consultant group specializing in Microsoft technologies.
Occupation: Web Developer
Location: Canada Canada

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 41 (Total in Forum: 41) (Refresh)FirstPrevNext
GeneralMailAttachment obsoletememberMember 350908012:32 5 Nov '08  
GeneralError this coding ( please reply immediatly )membersivavivekanantha3:37 8 Jul '08  
Questionemail sendingmembervishnoithegreat23:47 12 May '08  
GeneralThe FileUpLoad controlsmemberraremother7:20 14 Sep '07  
GeneralWrapping an email with attachments as one attachment in C# .net 2005memberFire starter22:56 12 Jul '07  
Questionwhat if it is hosted in a websitememberlovedotnet2:17 7 Jun '07  
AnswerRe: what if it is hosted in a websitememberLuc Archambault13:31 7 Jun '07  
GeneralYou don't need to save posted file on the diskmemberSimon Mourier5:07 2 Apr '07  
Generaltell me how to create inbox??membersaeee0:23 5 Mar '07  
Generalhow can i recieve email at local servermembersaeee22:02 27 Feb '07  
GeneralRe: how can i recieve email at local servermemberLuc Archambault8:28 28 Feb '07  
GeneralRe: how can i recieve email at local servermembersaeee19:22 4 Mar '07  
GeneralRe: how can i recieve email at local servermembersaeee22:28 8 Mar '07  
GeneralCompilation errormemberRolf6721:32 29 Jul '06  
GeneralRe: Compilation errormembertiux9:43 15 Jun '07  
QuestionNot Compatible With ASP.NET 2.0?memberOzma610:18 19 Apr '06  
AnswerRe: Not Compatible With ASP.NET 2.0?memberLuc Archambault12:52 19 Apr '06  
Questionhments.NET mail servermemberonlyelnaz22:19 28 Feb '06  
GeneralERROR RUNNING ITmembernguyenhh15:19 15 Sep '05  
GeneralRe: ERROR RUNNING ITmemberVasudevan Deepak Kumar0:10 31 Oct '05  
Generalquestion about compiling.memberjeniveve366:27 24 Jun '05  
GeneralRe: question about compiling.memberVasudevan Deepak Kumar0:12 31 Oct '05  
GeneralAttachments from desktopmembermajanjua8:28 13 Jun '05  
GeneralRe: Attachments from desktopmemberberndmarquard2:00 16 Jan '06  
GeneralThis is greatsussAnonymous2:01 11 May '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 25 Jan 2005
Editor: Smitha Vijayan
Copyright 2004 by Luc Archambault
Everything else Copyright © CodeProject, 1999-2008
Web20 | Advertise on the Code Project