0

Is there any general way to add an attachment to a mail read from an stream using MimeKit?

I need something like this

var message = MimeMessage.Load(inputStream);
var newMessage = AddSomeInfoAttachment(message);
newMessage.WriteTo(outputStream)

The part in question is "AddSomeInfoAttachment(message)". The attachment (for now) is just a text file (a string in fact).

It appears to be easy if you create a new message (http://www.mimekit.net/docs/html/Creating-Messages.htm) but I suspect that it's way more complicated to start with an already created one (for instance: Where in the MIME tree is supposed to go the attachment? Do I have to copy all other parts to a newMessage or can I just modify the original message in place?)

So far the only "Attachments" collections (with an Add) I see is using a BodyBuilder and I suspect that is not that easy with an already loaded MimeMessage.

1 Answers1

1

In the most common scenario, the following code snippet should do what you want/expect:

var message = MimeMessage.Load(fileName);
var attachment = new TextPart("plain") {
    FileName = "attachment.txt",
    ContentTransferEncoding = ContentEncoding.Base64,
    Text = attachmentText
};

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);
jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • Just curious about it: Any examples of a "non common scenario"? (i.e.: In what case the code above doesn't do the right thing?). BTW, I'm very grateful about your MailKit. Thanks. :-) – Yanko Hernández Alvarez Dec 26 '22 at 13:29
  • 1
    I can't think of one, but I don't want to claim that this will be correct in 100% of scenarios :-) – jstedfast Dec 28 '22 at 16:44