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);
}