Send Multiple InMemory Attachments Using FileUpload Controls

Posted by bullpit on Geeks with Blogs See other posts from Geeks with Blogs or by bullpit
Published on Wed, 09 Feb 2011 16:16:11 GMT Indexed on 2011/02/09 23:26 UTC
Read the original article Hit count: 303

Filed under:
I wanted to give users an ability to send multiple attachments from the web application. I did not want anything fancy, just a few FileUpload controls on the page and then send the email. So I dropped five FileUpload controls on the web page and created a function to send email with multiple attachments.
Here’s the code:
public static void SendMail(string fromAddress, string toAddress, string subject, string body, HttpFileCollection fileCollection)
    {
        // CREATE THE MailMessage OBJECT
        MailMessage mail = new MailMessage();
 
        // SET ADDRESSES
        mail.From = new MailAddress(fromAddress);
        mail.To.Add(toAddress);
 
        // SET CONTENT
        mail.Subject = subject;
        mail.Body = body;
        mail.IsBodyHtml = false;
              
        // ATTACH FILES FROM HttpFileCollection
        for (int i = 0; i < fileCollection.Count; i++)
        {
            HttpPostedFile file = fileCollection[i];
            if (file.ContentLength > 0)
            {
                Attachment attachment = new Attachment(file.InputStream, Path.GetFileName(file.FileName));
                mail.Attachments.Add(attachment);
            }
        }
 
        // SEND MESSAGE
        SmtpClient smtp = new SmtpClient("127.0.0.1");
        smtp.Send(mail);
    }
And here’s how you call the method:
protected void uxSendMail_Click(object sender, EventArgs e)
    {
        HttpFileCollection fileCollection = Request.Files;
        string fromAddress = "[email protected]";
        string toAddress = "[email protected]";
        string subject = "Multiple Mail Attachment Test";
        string body = "Mail Attachments Included";
        HelperClass.SendMail(fromAddress, toAddress, subject, body, fileCollection);       
    }

© Geeks with Blogs or respective owner