5

Is it possible to add IFormFile files to email attachments in .net core? I am getting files from angular using formdata.

 for (let file of this.files) {
  this.formData.append("Files", file.nativeFile);
}

    MailMessage mail = new MailMessage();
    SmtpClient smtp = new SmtpClient
    {
        Host = "smtp.sendgrid.net",
        Port = 25,
        Credentials = new System.Net.NetworkCredential("key", "pass")
    };


    [HttpPost("[action]")]
    public IActionResult UploadFiles(IList<IFormFile> Files)
    {
        foreach (var file in Files)
        {
            using (var stream = file.OpenReadStream())
            {
                var attachment = new Attachment(stream, file.FileName);
                mail.Attachments.Add(attachment);
            }
        }
        mail.To.Add("email@hotmail.com");
        mail.From = from;
        mail.Subject = "Subject";
        mail.Body = "test";
        mail.IsBodyHtml = true;
        smtp.Send(mail);
Nakres
  • 1,212
  • 11
  • 27
  • Are you adding attachments to a collection? What does the object being sent to your controller look like? – Leonardo Wildt Jan 09 '19 at 02:20
  • I am trying to add files to mail attachment. If i save files to a folder then attach them to the mail then everything works but I want to do the same thing without saving the files to my server. – Nakres Jan 09 '19 at 13:19

1 Answers1

11

I am able to attach IFormFile files to mail now without saving the files to the server. I am converting files to byte array. The reason I am converting to byte array is that my website is in Azure and Azure converts files to byte array. Otherwise I was not able to open pdf files. It was throwing following error: ... it was sent as an email attachment and wasn't correctly decoded.

enter image description here

Working code:

[HttpPost("[action]")]
public IActionResult UploadFiles(IList<IFormFile> Files)
{
   foreach (var file in Files)
            {
                if (file.Length > 0)
                {
                    using (var ms = new MemoryStream())
                    {
                        file.CopyTo(ms);
                        var fileBytes = ms.ToArray();
                        Attachment att = new Attachment(new MemoryStream(fileBytes), file.FileName);
                        mail.Attachments.Add(att);
                    }
                }
            }
            mail.To.Add("someemamil@hotmail.com");
            mail.From = from;
            mail.Subject = "subject";
            mail.Body = "test";
            mail.IsBodyHtml = true;
            smtp.Send(mail);
            mail.Dispose();
Nakres
  • 1,212
  • 11
  • 27