将IFormFile附加到邮件而不保存文件

时间:2019-01-09 00:07:54

标签: angular .net-core iformfile

是否可以将IFormFile文件添加到.net core中的电子邮件附件?我正在使用formdata从angular获取文件。

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

1 个答案:

答案 0 :(得分:2)

我现在可以将IFormFile文件附加到邮件中,而无需将文件保存到服务器。我正在将文件转换为字节数组。我转换为字节数组的原因是我的网站位于Azure中,而Azure将文件转换为字节数组。否则,我将无法打开pdf文件。它抛出以下错误: ...它作为电子邮件附件发送,并且未正确解码。

enter image description here

工作代码:

[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();