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

14 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.

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: