How to upload multiple files from a static html form and attach them in an email using C#

Bookmark and Share
Monday, April 06 2009

I've come across a few forums posts where people have asked this question under special circumstances.

The scenario: A web application with some sort of web service or a simple web handler needs to request multiple files and email them, but where the data is posted from disparate clients.  These clients could be static html forms, desktop applications, etc.

The following is one simplified example of how you might achieve this..

First, let's look at the html form.

<form id="MyForm" method="post" enctype="multipart/form-data" action="http://mydomain.com/FeedMe.ashx">
<p>Name: <input type="text" id="name" name="name" ></input></p>
<p>Email: <input type="text" id="email" name="email" ></input></p>
<p>File 1: <input type="text" id="file1" name="file1" ></input></p>
<p>File 2: <input type="text" id="file2" name="file2" ></input></p>
<p><input type="submit" id="submit" name="submit" value="Submit" ></input></p>
</form>

 

We are submitting two files, file1 and file2, to a web handler called FeedMe.ashx.

Now let's take a look at the code within our web hander:

using System;
using System.Collections;
using System.Web;
using System.Net.Mail;
 
namespace MyWebHandler
{
 public class EmailFiles : IHttpHandler
 {
   public void ProcessRequest(HttpContext context)
    {
     string name = context.Request.Form["name"]
     string email = context.Request.Form["email"];
 
      MailMessage mail = new MailMessage();
      mail.From = new MailAddress(email, name);
      mail.Subject = “You haz a filez!”;
      mail.Body = “You can haz multiple filez now!”;
      mail.To.Add(new MailAddress(“me@email.com”, “me”));
 
      HttpFileCollection MyFiles context.Request.Files;
      foreach (String fileKey in MyFiles)
      {
        mail.Attachments.Add(new Attachment(MyFiles[fileKey].InputStream, MyFiles[fileKey].FileName.ToString()));
      }
 
      SmtpClient client = new SmtpClient("localhost");
      client.Send(mail);
      context.Response.Write(“response to client”);
    }
 
    public bool IsReusable
      {
        get
          {
            return false;
          }
      }
    }
 }
 

Looking at the web handler, first we request our name and email form elements from the form submission:

     string name = context.Request.Form["name"]
     string email = context.Request.Form["email"];
 
Next, we create our email: 
 
      MailMessage mail = new MailMessage();
      mail.From = new MailAddress(email, name);
      mail.Subject = “You haz filez!”;
      mail.Body = “You can haz multiple filez now!”;
      mail.To.Add(new MailAddress(“me@email.com”, “me”));
 
 

Now, we'll request the submitted files from context and assign them to MyFiles.

Using a foreach loop, we loop through the collection and grab the key for each posted file.

Once we have the key, we Add a new mail attachement, passing the InputStream of MyFiles for the given key as the File, along with the name of that file.

(Note, you will want to filter out the local path in the FileName)

 

 

      HttpFileCollection MyFiles context.Request.Files;
      foreach (String fileKey in MyFiles)
      {
        mail.Attachments.Add(new Attachment(MyFiles[fileKey].InputStream, MyFiles[fileKey].FileName.ToString()));
      }

 

Once we've cycled through all the files posted and attached them to the email, we'll send the email:

      SmtpClient client = new SmtpClient("localhost");
      client.Send(mail);
      context.Response.Write(“response to client”);

 

Tagged as: , , , , , ,

Bookmark and Share

24 comment(s) so far

    • debt reduction help
    •  avatar
       
      Jul 20, 2011

      My partner cuts up polystyrene (plastic foam) as a way of recycling materials for packaging. It's very efficient but the build up of static electricity slows the job down and drives her crazy.

    • Technomate
    •  avatar
       
      Nov 27, 2011

      Depends whether you want to download files more than once a day or simultaneousness. You can try Rapid8 dot com but its full of viruses so make sure you have antivirus. Or search on youtube for a premium account generator.

    • Web Design
    •  avatar
       
      Dec 07, 2011

      Now, we'll request the submitted files from context and assign them to MyFiles.

    • Best online dating
    •  avatar
       
      Dec 23, 2011

      You can try Rapid8 dot com but its full of viruses so make sure you have antivirus. Or search on youtube for a premium account generator.

    • uk golf holiday
    •  avatar
       
      Jan 21, 2012

      I appreciate everything you have added to my knowledge base.Admiring the time and effort you put into your blog and detailed information you offer!

    • domain name
    •  avatar
       
      Jan 21, 2012

      It's called server-side programming. Languages like ASP and PHP allow HTML to be generated

      dynamically.

    • laya rugs
    •  avatar
       
      Jan 31, 2012

      I've been trying to explore my phone settings and internet blogs on how to send multiple files, but when I try it it keeps on sending only one file. I have to send it one by one. It's really frustrating, especially when I need to send more than 20 files. Could somebody help me? It would really help. :) Thanks.

    • air framing nailer
    •  avatar
       
      Mar 10, 2012

      Just browse for your favorite Ethiopian artist and enjoy his or her music videos. To your convenience mgport has alphabetically sorted the ingredients of Ethiopian Music Videos by artists name to ease browsing.

    • document storage manchester
    •  avatar
       
      Mar 31, 2012

      I am sure you are planning to download from some site and upload to others and thinking you will be paid for all those. Forget all that man. No one is going to pay you a single penny.

    • party singers
    •  avatar
       
      Apr 16, 2012

      If you'd like to send multiple files, then connect the devices to a computer and do it all on there by dragging the files from one folder to another.

    • Seo UK
    •  avatar
       
      May 01, 2012

      The following is one simplified example of how you might achieve this..

    • Victoria Title Search
    •  avatar
       
      May 04, 2012

      I've already seen answers about saving INDIVIDUAL files, which I've seen already. But I just got a flash-drive and I need to transfer about 150 files from G-Docs to my flash drive. When I select multiple files, there is only a save as HTML option....Thanks..

    • abercrombie
    •  avatar
       
      May 09, 2012

      I have been searching for quite some time for information on this topic and no doubt your website saved my time and I got my desired information. Your post has been very helpful. Thanks.

Post your comment

Thanks for your comments


To use your gravatar, enter the email or username associated with that gravatar.

  • Comment

 

Office Cam

Search

My Tweets

  • johnny861: I signed the petition to bring Pliny The Elder to Texas! http://t.co/C2uHGHa1
  • johnny861: RT @Han_Cholo: The glow on top is the aura of it's awesomeness *tear* http://t.co/NwCDKlC7
  • johnny861: If the May 21st rapture really happens, my hope is someone gets recorded yelling "To the Cloud!" just before they vanish in a puff of smoke.
  • johnny861: LA Lakers just can't handle a total beat down can they? Pathetic sportsmanship. Go MAVS!
  • johnny861: RT @tohams: Spinal Tap reference at #Dreamcore #FTW
  • johnny861: RT @john_boone: how to use multiple versions of jQuery (not my blog, just a smart guy): http://ow.ly/4E8Nn #dreamcore
  • johnny861: RT @awareweb: Great reception at #Dreamcore. Thanks to #Sitecore for arranging an opportunity for us all to connect.
 

Powered By: