I'm using Mailkit v2.2.0 to retrieve e-mails from an exchange server using IMAP. First, I read mails and process them, afterwards they will be deleted - if neccessary. Therefore, I connect to the IMAP server two times within a short time span.
private ImapClient GetImapClient(MailServerConnectionString connectionString) {
var client = new ImapClient();
if (connectionString.AcceptAllCertificates) {
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
}
client.Connect(connectionString.Server, connectionString.Port, connectionString.Encryption);
if (connectionString.AuthenticationRequired) {
client.Authenticate(connectionString.UserName, connectionString.Password);
}
return client;
}
Retrieve the mails:
using (var client = GetImapClient(config.ImapConnectionString)) {
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadWrite);
var items = inbox.Fetch(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.Size | MessageSummaryItems.Flags);
foreach (var item in items) {
var message = inbox.GetMessage(item.UniqueId);
var mail = message.Convert(includeAttachments);
mail.Seen = item.Flags?.HasFlag(MessageFlags.Seen) ?? false;
mail.UniqueId = item.UniqueId.Id;
result.Add(mail);
inbox.AddFlags(item.UniqueId, MessageFlags.Seen, true);
}
inbox.Close();
client.Disconnect(true);
}
After processing the mails, delete them:
using (var client = GetImapClient(config.ImapConnectionString)) {
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadWrite);
inbox.AddFlags(ids, MessageFlags.Deleted, true);
inbox.Expunge();
client.Disconnect(true);
}
Good to know:
Everything works just fine with the hMailServer, MS Exchange doesn't though.
The first connection works, the second connection fails.
The exception on the second connection:
An error occurred while attempting to establish an SSL or TLS connection.I'm using port 993 and
SecureSocketOptions.SslOnConnectboth times.