Search code examples
c#.net-core.net-5mailkitmimekit

MailKit-MimeKit - How to copy to Sent folder


I ama able to sent SMTP emails using MailKit & MimeKit and outlook is the client tool receiving these mails. Below code has been used and my Inbox has emails received.

var email = new MimeMessage
{
    Sender = MailboxAddress.Parse("<<from>>")
};
email.To.Add(MailboxAddress.Parse("<<to>>"));

email.Subject = "Test mail from Jaish";
var builder = new BodyBuilder();
builder.TextBody = "This is a test mail from Jaish Mathews";
email.Body = builder.ToMessageBody();

using var smtp = new SmtpClient();
smtp.LocalDomain = "<<domain>>";
smtp.Timeout = 10000;

smtp.Connect("<<host>>", 25, SecureSocketOptions.None);
var mailboxes = email.To.Mailboxes;
//Sending email
await smtp.SendAsync(email);
//Disconnecting from smtp
smtp.Disconnect(true);

Issue is that my "Sent" folder isn't keeping any track of these emails sent. How can I manually copy to my "Sent" folder"


Solution

  • Before I explain how to save the message in your Sent IMAP folder, I first want to bring attention to a few things.

    1. smtp.Timeout = 10000; It's probably best to not override the default timeout (which I believe is 120,000. 10000 is 10 seconds).
    2. You currently have a mix of sync and async calls to the SmtpClient. You should pick sync or async and stick with it (at least if it's all within the same method).

    Okay, now on to your question.

    using var imap = new ImapClient ();
    
    await imap.ConnectAsync ("<<host>>", 143 /* or 993 for SSL */, SecureSocketOptions.Auto).ConfigureAwait (false);
    await imap.AuthenticateAsync ("username", "password").ConfigureAwait (false);
    
    IMailFolder sent = null;
    if (imap.Capabilities.HasFlag (ImapCapabilities.SpecialUse))
        sent = imap.GetFolder (SpecialFolder.Sent);
    
    if (sent == null) {
        // get the default personal namespace root folder
        var personal = imap.GetFolder (imap.PersonalNamespaces[0]);
    
        // This assumes the sent folder's name is "Sent", but use whatever the real name is
        sent = await personal.GetSubfolderAsync ("Sent").ConfigureAwait (false);
    }
    
    await sent.AppendAsync (email, MessageFlags.Seen).ConfigureAwait (false);
    
    await imap.DisconnectAsync (true).ConfigureAwait (false);