我想將檔案從主機發送給注冊用戶,并以確認電子郵件作為附件。
我的電子郵件發件人類接受包含的訊息模型 public IFormFileCollection Attachments { get; set; }
我的問題:我無法從主機讀取檔案并將其轉換為 IFormFile。
這是我的一段代碼:
var pathToEmailAttachment = _webHostEnvironment.WebRootPath
Path.DirectorySeparatorChar.ToString()
"pdf"
Path.DirectorySeparatorChar.ToString()
"MyFile.pdf";
IFormFile file;
using (var stream = System.IO.File.OpenRead(pathToEmailAttachment))
{
file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name));
}
var message = new Message(new string[] { user.Email }, messageSubject, emailMessage, new FormFileCollection() { file });
await _emailSender.SendEmailAsync(message);
訊息模型:
public class Message
{
public List<MailboxAddress> To { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
public IFormFileCollection Attachments { get; set; }
public Message()
{
}
public Message(IEnumerable<string> to, string subject, string content, IFormFileCollection attachments)
{
To = new List<MailboxAddress>();
To.AddRange(to.Select(x => new MailboxAddress(x, x)));
Subject = subject;
Content = content;
Attachments = attachments;
}
}

任何建議或幫助將不勝感激。
uj5u.com熱心網友回復:
可能有 2 個問題,不正確的FormFile實體化和檔案流的提前關閉。因此,您可以嘗試在此答案和擴展陳述句的FormFile幫助下修復創建using
using (var stream = System.IO.File.OpenRead(pathToEmailAttachment))
{
file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
{
Headers = new HeaderDictionary(),
ContentType = "you content type"
};
var message = new Message(new string[] { user.Email }, messageSubject, emailMessage, new FormFileCollection() { file });
await _emailSender.SendEmailAsync(message);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/397528.html
上一篇:使用user.Email和await_userManager.GetEmailAsync(user)有什么區別?
