您好,我们正在尝试使用 MailKit 开发邮件发送系统。我们有一组使用 WORD 创建并保存为 MHTML 文件的电子邮件模板。当我们使用 MailKit 从 MHT 文件创建 MimeMessage 时,整个事情工作正常。
但是在创建此消息后,我无法找到添加附件的方法。
目前我们正在尝试以下措施。
private void SendEmail(string templatePath, List<string> attachments)
{
// Load the MHT Template
var mimeMessage = MimeMessage.Load(templatePath);
mimeMessage.From.Add(new MailBoxAddress("[email protected] /cdn-cgi/l/email-protection"));
mimeMessage.To.Add(new MailBoxAddress("[email protected] /cdn-cgi/l/email-protection"));
foreach (var attachment in attachments)
{
var fileAttachment = new MimePart()
{
ContentObject = new ContentObject(File.OpenRead(Path.Combine(attachment), ContentEncoding.Default),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Binary,
FileName = Path.GetFileName(attachment)
};
// Attachments is a read only Enumerable here.
mimeMessage.Attachments.Add
}
}
您需要遍历消息的 MIME 树结构,直到找到Multipart
您想要添加“附件”,然后使用 Multipart.Add() 方法。
请记住,消息是嵌套的树结构,而不是只有 1 个消息正文(甚至只有 2 个)和附件列表的明确定义的结构。它比这复杂得多,所以 MimeMessage.Attachments 实际上没有办法“做正确的事情”。
对于一般情况,您可能可以这样做:
var message = MimeMessage.Load(fileName);
var attachment = new MimePart("application", "octet-stream") {
FileName = attachmentName,
ContentTransferEncoding = ContentEncoding.Base64,
Content = new MimeContent(attachmentStream)
};
if (!(message.Body is Multipart multipart &&
multipart.ContentType.Matches("multipart", "mixed"))) {
// The top-level MIME part is not a multipart/mixed.
//
// Attachments are typically added to a multipart/mixed
// container which tends to be the top-level MIME part
// of the message (unless it is signed or encrypted).
//
// If the message is signed or encrypted, though, we do
// do not want to mess with the structure, so the correct
// thing to do there is to encapsulate the top-level part
// in a multipart/mixed just like we are going to do anyway.
multipart = new Multipart("mixed");
// Replace the message body with the multipart/mixed and
// add the old message body to it.
multipart.Add(message.Body);
message.Body = multipart;
}
// Add the attachment.
multipart.Add(attachment);
// Save the message back out to disk.
message.WriteTo(newFileName);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)