1

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"

jstedfast
  • 35,744
  • 5
  • 97
  • 110
Jaish Mathews
  • 766
  • 1
  • 9
  • 25
  • Does this answer your question? [Why emails sent by smtpclient does not appear in sent items](https://stackoverflow.com/questions/24257524/why-emails-sent-by-smtpclient-does-not-appear-in-sent-items) – Martin Staufcik Mar 11 '22 at 07:53
  • Thanks 1st of all. This link explanation is more leaning towards .NET 4.x . I am using .NET 5 and I heard that I can use IMap connection in place of SMTP using MailKit & MimeKit libraries. Then access "Sent" folder to use "append()" method to drop mails in it. That's all theory I read and couldn't see much implementation ref. – Jaish Mathews Mar 11 '22 at 12:54

1 Answers1

3

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);
jstedfast
  • 35,744
  • 5
  • 97
  • 110