Update/Replace/AddAttachment to draft but keep the unique message id #1845
-
Hi there, I want to add an attachment to a existing draft email and sync the change back to the email server without sending the email. I ended up with this code: var folder = await _imapClient.GetFolderAsync(folderPath, cancellationToken);
await folder.OpenAsync(FolderAccess.ReadWrite, cancellationToken);
var message = await folder.GetMessageAsync(uniqueId.Value, cancellationToken);
if (message == null)
throw new EmailNotFoundException($"The draft email with id '{emailId}' could not be found.");
var builder = new BodyBuilder {
TextBody = message.TextBody,
HtmlBody = message.HtmlBody
};
await builder.Attachments.AddAsync(attachmentFileName, attachmentStream, cancellationToken);
message.Body = builder.ToMessageBody();
// and here is the problem
var messageId = await folder.ReplaceAsync(uniqueId.Value, message, MessageFlags.Draft, cancellationToken);
if (!messageId.HasValue)
throw new EmailCreationException("The email draft could not be created.");
Debug.Assert(uniqueId.Value.Equals(messageId.Value), "The unique id of the message should not change.");
// this leads to an update of the draft, but also changes the unique id, which I want to keep Is there another/better way to update the draft without changing the uniqueId of my email? The reason I want to archive this, is because i want to add multiple attachments to one email before sending it. Each of this attachments is provided one by one. So I want to use the mail server as kind of storage for the "complete" email draft I build with all the information and attachments. And once the mail draft is complete I will send it via smtp. Sincerly snailcatcher |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
The way you are doing it is the recommended way. The UID changing is a side effect, most likely, of the server not supporting the REPLACE command, so MailKit has to work-around that by appending a new message to the Drafts folder (which means it'll get a new UID). Clients cannot override the server's choice of UID. |
Beta Was this translation helpful? Give feedback.
If you want to incrementally add attachments, it would be best to download the entire message and add them w/o the use of the BodyBuilder (BodyBuilder, honestly, is for constructing new messages and not adding to existing messages).
The BodyBuilder.ToMessageBody() method replaces the existing message body with the new content.
You can do something more like this: