danzuep / MailKitSimplified

Send and receive emails easily, fluently, with one line of code for each operation.
MIT License
79 stars 10 forks source link

How to connect STARTTLS enabled server? #19

Closed mubassir-hasan closed 1 year ago

mubassir-hasan commented 1 year ago

How can convert this configuration for ImapReceiver

            var client = new ImapClient();
            client.CheckCertificateRevocation = false;
            client.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13;
            client.ServerCertificateValidationCallback = (s, c, h, e) => true;
            client.Connect(item.IMAPHost, item.IMAPPort, MailKit.Security.SecureSocketOptions.StartTls);
            client.Authenticate(item.Email, item.IMAPPassword);
danzuep commented 1 year ago

If you're using the latest version then TLS is used by default if it is supported, but if you specifically want to disable SSL then the easiest way at the moment would be to pass your ImapClient in to the ImapReceiver constructor. Here's an example using IoC or Dependency Injection (using TLS 1.0 or TLS 1.1 will generate a warning saying not to use them):

            services.AddTransient<IImapClient>((serviceProvider) => {
                var client = new ImapClient();
                client.CheckCertificateRevocation = false;
                client.SslProtocols = SslProtocols.Tls12;
#if NET5_0_OR_GREATER
                client.SslProtocols |= SslProtocols.Tls13;
#endif
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                return client;
            });
danzuep commented 1 year ago

Here's an simple example of how you'd do it without IoC or DI: new ImapReceiver(Options.Create(new EmailReceiverOptions()), logger, new LogFileWriter(), client, loggerFactory);

mubassir-hasan commented 1 year ago

Thank you for your quick response. It worked like charm :). Feels dumb, Just another quick question where should I use this code background service! Tried with .net core web project BackgroundService but not getting any updates.

await imapReceiver.MonitorFolder
    .SetMessageSummaryItems().SetIgnoreExistingMailOnConnect()
    .OnMessageArrival((messageSummary) => OnArrivalAsync(messageSummary))
    .IdleAsync(cancellationToken);

Email server support idle connection checked with this code _client.Capabilities.HasFlag(ImapCapabilities.Idle)

danzuep commented 1 year ago

I've made an example using a worker service so read through that then let me know if you're still not sure.

mubassir-hasan commented 1 year ago

Thank you for Simplified solution

danzuep commented 1 year ago

Glad you like it @mubassir-hasan! To show your appreciation, please star the repository in the top right corner ⭐ 🌟 🤩