3

是否可以将 IFormFile 文件添加到 .net 核心中的电子邮件附件?我正在使用 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);
4

1 回答 1

8

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

在此处输入图像描述

工作代码:

[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();
于 2019-01-09T15:55:45.557 回答