Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Uploaded File as attachment

I am trying to get an 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);

MailMessage message = new MailMessage();

//*****useless stuff********
message.To.Add("[email protected]");
message.Subject = "test";
message.From = new MailAddress("[email protected]");
message.IsBodyHtml = true;
message.Body = "testing";
 //*****useless stuff********

//Fault line
message.Attachments.Add(new Attachment(file, 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 without the attachment. Do I need to save the file first and then add to attachment?

like image 206
nikhil Avatar asked Dec 13 '11 22:12

nikhil


2 Answers

You do NOT need to, nor should you, save attachments to the server unnecessarily. ASP Snippets has an article on how to do it in ASP.NET WebForms.

Doing it in C# MVC is even nicer:

public IEnumerable<HttpPostedFileBase> UploadedFiles { get; set; }

var mailMessage = new MailMessage();
// ... To, Subject, Body, etc

foreach (var file in UploadedFiles)
{
    if (file != null && file.ContentLength > 0)
    {
        try
        {
            string fileName = Path.GetFileName(file.FileName);
            var attachment = new Attachment(file.InputStream, fileName);
            mailMessage.Attachments.Add(attachment);
        }
        catch(Exception) { }
    }
}
like image 84
Serj Sagan Avatar answered Oct 19 '22 03:10

Serj Sagan


Following in the footsteps of Serj Sagan, here's a handler using webforms, but with <input type="file" name="upload_your_file" /> instead of the <asp:FileUpload> control:

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

This is useful if you don't need (or can't add) a runat="server" on your form tag.

like image 45
Michael Avatar answered Oct 19 '22 04:10

Michael