简体   繁体   English

MimeKit将附件添加到从mht文件加载的邮件中

[英]MimeKit add attachments to a message loaded from mht file

Hi We are trying to develop a mail sending system using MailKit. 嗨,我们正在尝试使用MailKit开发邮件发送系统。 We have a set of Email Templates which are created using WORD and saved as MHTML files. 我们有一组使用WORD创建并保存为MHTML文件的电子邮件模板。 The whole thing is working fine, when we use MailKit to create a MimeMessage from the MHT file. 当我们使用MailKit从MHT文件创建MimeMessage时,整个工作正常。

But post creating this message, I am not able to see a way of adding attachments to this. 但是创建此消息后,我看不到添加附件的方法。

Currently we are trying the following. 目前,我们正在尝试以下方法。

private void SendEmail(string templatePath, List<string> attachments)
    {
        // Load the MHT Template
        var mimeMessage = MimeMessage.Load(templatePath);

        mimeMessage.From.Add(new MailBoxAddress("test@Test.com"));
        mimeMessage.To.Add(new MailBoxAddress("test@Test.com"));

        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
        }

    }

You will need to traverse the MIME tree structure of the message until you find the Multipart that you would like to add the "attachment" to and then use the Multipart.Add() method. 您需要遍历消息的MIME树结构,直到找到Multipart ,你想在“附件”添加到,然后使用Multipart.Add()方法。

Keep in mind that a message is a nested tree structure and not a well-defined structure which has only 1 message body (or even just 2) and a list of attachments. 请记住,一条消息是一个嵌套的树结构,而不是一个只有一个消息主体(甚至只有2个)和附件列表的定义明确的结构。 It's a whole lot more complicated than that, so there's literally no way for MimeMessage.Attachments to "do the right thing". 比这复杂得多,因此MimeMessage.Attachments实际上没有办法“做正确的事”。

I add the attachment by the BodyBuilder: 我通过BodyBuilder添加附件:

BodyBuilder _body = new BodyBuilder
{
    HtmlBody = message
};
_body.Attachments.Add(_fileName, _stream);
_email.Body = _body.ToMessageBody();

See this post stackoverflow 看到这篇文章stackoverflow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM