.Net Core 5 web api 使用 mimekit 和 mailkit 的电子邮件附件

.Net Core 5 web api Email Attachment using mimekit and mailkit

我有一个来自客户端的文件,如下所示:

ContentType = "application/octet-stream"

其中一个是 pdf 文件。似乎正在发生的事情是我没有从流中获取文件,并且在打开电子邮件中的附件时文件已损坏。这是我的代码:

客户端

Angular:

createPdf(): {
  var dataURI = doc.output('datauristring');
  return dataURI ? dataURI : "";
}

createMail(): void {
    var blob = new Blob([this.createPdf()], { type: 'application/pdf' });
    var fileOfBlob = new File([blob], this.data.accountName + '_' + this.data.exceptionDate + '_' + 'ExceptionRequest.pdf');
    const mail: FormData = new FormData();
    mail.append('ToEmail', this.data.contactEmail);
    mail.append('Subject', 'Test');
    mail.append('Body', 'Test Email');
    mail.append('Attachments', fileOfBlob);

    console.log(fileOfBlob);

    this.mailService.createMail(mail)
      .subscribe(res => {
        console.log(res);
      });
  }

服务器端:

型号:

public class MailRequest
    {
        public string ToEmail { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public IFormFile Attachments { get; set; }
    }

服务:

        public async Task SendEmailAsync(MailRequest mailRequest)
        {
            var email = new MimeMessage();
            email.Sender = MailboxAddress.Parse(_mailSettings.Mail);
            email.To.Add(MailboxAddress.Parse(mailRequest.ToEmail));
            email.Subject = mailRequest.Subject;

            var builder = new BodyBuilder();
            byte[] fileBytes;
            if (mailRequest.Attachments != null)
            {
                var file = mailRequest.Attachments;
                if (file.Length > 0)
                {
                    using (var ms = new MemoryStream())
                    {
                        file.CopyTo(ms);
                        fileBytes = ms.ToArray();
                    }
                    builder.Attachments.Add(file.FileName, fileBytes, MimeKit.ContentType.Parse(MediaTypeNames.Application.Pdf));
                }
            }
            builder.HtmlBody = mailRequest.Body;
            email.Body = builder.ToMessageBody();
            using var smtp = new SmtpClient();
            smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls);
            smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password);
            await smtp.SendAsync(email);
            smtp.Disconnect(true);
        }

控制器:

[HttpPost("send")]
        public async Task<IActionResult> SendMail([FromForm] MailRequest request)
        {
            try
            {
                await _mailService.SendEmailAsync(request);
                return Ok();
            }
            catch (Exception ex)
            {
                throw;
            }
        }

我在想我需要将流解析为 pdf,但不确定我的代码中哪里出错了。有没有人知道我在上面的 SendEmailAsync 服务中可能做错了什么?

mailRequest.Attachments 是一个 List。您必须处理列表中的每一项。

foreach (var file in mailRequest.Attachments)
{
    if (file.Length > 0)
    {
        using (var ms = new MemoryStream())
        {
            file.CopyTo(ms);
            fileBytes = ms.ToArray();
        }
        builder.Attachments.Add(file.FileName, fileBytes, MimeKit.ContentType.Parse(MediaTypeNames.Application.Pdf));
    }
}

答案是我没有在客户端的函数 createPdf() 中将其作为 blob 传递。所以,我需要做的就是像这样传递它:

Angular代码:

createPdf(): {
  var blob = doc.output('blob');
  return blob;
}

这样当传递给 createMail() 函数时它仍然是一个 blob。现在完美运行了。