【发布时间】:2021-12-28 09:38:59
【问题描述】:
我想从主机向注册用户发送一个文件,并附上确认电子邮件。
我的电子邮件发件人类接受包含 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;
}
}
任何建议或帮助将不胜感激。
【问题讨论】:
-
我建议将
Message转换为内部实体,然后添加额外的附件将是微不足道的。 -
我认为问题在于读取文件并将其填充到 IFormFile 中。也许我需要更改 using 语句。
-
确定文件存在于 wwwroot/pdf 文件夹中吗?
-
是的,它在 wwwroot/pdf 中。
标签: c# asp.net-core iformfile