Send Uploaded File as attachment

Total Post:108

Points:756
C# 
C#
 1271  View(s)
Ratings:
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;
        fileupload.SaveAs(saveLocation);           
        MailMessage message = new MailMessage();
        //*****useless stuff********
        message.To.Add("abc@xxx.com");
        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");
        smtp.Send(message);

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.

  1. Post:378

    Points:2694
    Re: Send Uploaded File as attachment

    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);
        mailMessage.Attachments.Add(attachment);
    }

      Modified On Apr-04-2018 07:01:43 AM

Answer