Home > DeveloperSection > Forums > Send Uploaded File as attachment
john rob

Total Post:108

Posted on    August-25-2014 1:23 AM

 C# C# 

 1 Reply(s)
 934  View(s)
Rate this:

I am trying to get the uploaded file to be sent as an attachment in my ashx file, Here is the code I am using

        HttpPostedFile fileupload = context.Request.Files[0];

        //filename w/o the path

        string file = Path.GetFileName(fileupload.FileName);

        string saveLocation = HttpContext.Current.Server.MapPath("UploadDirName") + "\\" + file;


        MailMessage message = new MailMessage();

        //*****useless stuff********


        message.Subject = "test";

        message.From = new MailAddress("test@aaa.com");

        message.IsBodyHtml = true;

        message.Body = "testing";

         //*****useless stuff********

        //Fault line

        message.Attachments.Add(new Attachment(saveLocation, MediaTypeNames.Application.Octet))

        //Send mail

        SmtpClient smtp = new System.Net.Mail.SmtpClient("xxxx", 25);

        smtp.UseDefaultCredentials = false;

        smtp.Credentials = new NetworkCredential("xxx", "xxxx");


I am able to send the email w/o the attachment. 

Do I need to save the file first? and then add to attachment ? 

I haven't worked much on form processing in asp.net.

Sumit Kesarwani

Total Post:378

Posted on    August-25-2014 2:22 AM

Hi John, 
try this:

HttpPostedFile file = Request.Files["upload_your_file"];

if (file != null && file.ContentLength > 0)


    string fileName = Path.GetFileName(file.FileName);

    var attachment = new Attachment(file.InputStream, fileName);



Don't want to miss updates? Please click the below button!

Follow MindStick