Search code examples
angular.net-coreiformfile

Attach IFormFile to mail without saving the file


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 protected]");
        mail.From = from;
        mail.Subject = "Subject";
        mail.Body = "test";
        mail.IsBodyHtml = true;
        smtp.Send(mail);

Solution

  • 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("[email protected]");
                mail.From = from;
                mail.Subject = "subject";
                mail.Body = "test";
                mail.IsBodyHtml = true;
                smtp.Send(mail);
                mail.Dispose();