Send Email in C# with MailKit (.NET 10): SMTP and Errors

Last updated: October 26, 2026 · Tested with .NET 10.0.12 (SDK 10.0.401), MailKit 4.18.2 against a local smtp4dev 3.15.0 server (plain SMTP, STARTTLS with login, implicit TLS on 465), Windows 11

Short answer: to send email from C# on .NET 10, install MailKit, build a MimeMessage (use BodyBuilder for HTML, a plain-text fallback and attachments), then ConnectAsync with the right SecureSocketOptions for the port, AuthenticateAsync, SendAsync and DisconnectAsync. Most “MailKit doesn’t work” reports come from three things: the wrong TLS option for the port (587 is StartTls, 465 is SslOnConnect), a certificate the client doesn’t trust, and providers that no longer accept a plain password. Below is the code I ran and every error I reproduced, with the exact message.

You see this Cause Fix
SslHandshakeException with inner Cannot determine the frame size or a corrupted frame was received. SslOnConnect on a STARTTLS port (587) Use StartTls on 587
SslHandshakeException: terminated in a root certificate which is not trusted Self-signed or internal certificate Trust the certificate; validate it in a callback only in development
TimeoutException: Operation timed out after ... milliseconds None (or Auto on a non-465 port) against implicit TLS SslOnConnect for implicit-TLS ports
NotSupportedException: The SMTP server does not support the STARTTLS extension. StartTls against a server without TLS StartTlsWhenAvailable or None (local test servers only)
AuthenticationException: 535: Authentication failure Wrong user name or password, or the provider wants OAuth/app passwords Check the account settings below
ServiceNotAuthenticatedException: Authentication is required Sending without AuthenticateAsync Authenticate after connecting
SocketException: No connection could be made because the target machine actively refused it. Wrong host or port, or a firewall Check host and port

How I Tested It

I didn’t want to test with anyone’s real mailbox, so every case ran against smtp4dev, a local SMTP server that captures messages instead of delivering them. I started four instances: plain SMTP on 2525, STARTTLS with a required login on 2587, and implicit TLS on 2465 and 465 (the last two with smtp4dev’s auto-generated self-signed certificate). A console app ran each case; the output blocks below are copied from it, and the “received” data comes from smtp4dev’s API. I didn’t test against Gmail or Microsoft accounts; their settings below come from the providers’ own help pages.

Step 1: Install MailKit

dotnet add package MailKit

MailKit brings MimeKit with it. Microsoft’s own documentation for System.Net.Mail.SmtpClient says not to use that class for new development and points to MailKit instead, because it doesn’t support many modern protocols.

Step 2: Build the Message

BodyBuilder creates the right MIME structure for you: an HTML part, a plain-text alternative for clients that don’t render HTML (and for spam filters, which like having both), and attachments:

static MimeMessage BuildMessage()
{
    var message = new MimeMessage();
    message.From.Add(new MailboxAddress("Shop", "noreply@example.test"));
    message.To.Add(new MailboxAddress("Asha", "asha@example.test"));
    message.Subject = "Your order #1042 has shipped";

    var body = new BodyBuilder
    {
        TextBody = "Your order #1042 has shipped. Track it at https://example.test/orders/1042",
        HtmlBody = "<p>Your order <b>#1042</b> has shipped.</p><p><a href=\"https://example.test/orders/1042\">Track it</a></p>"
    };
    body.Attachments.Add("invoice-1042.pdf", "%PDF-1.7 test invoice"u8.ToArray(), new ContentType("application", "pdf"));
    message.Body = body.ToMessageBody();
    return message;
}

The message smtp4dev received has exactly that structure:

Content-Type: multipart/mixed | Subject: Your order #1042 has shipped
  part: multipart/mixed
  part: multipart/alternative
  part: text/plain
  part: text/html
  part: application/pdf invoice-1042.pdf

Step 3: Connect, Authenticate, Send

using var smtp = new SmtpClient { Timeout = timeoutMs };
await smtp.ConnectAsync(host, port, options);
await smtp.AuthenticateAsync(user, password);
var response = await smtp.SendAsync(BuildMessage());
await smtp.DisconnectAsync(true);

SmtpClient here is MailKit.Net.Smtp.SmtpClient; if the file also imports System.Net.Mail, the name is ambiguous, so remove that using. SendAsync returns the server’s final response. Against the STARTTLS server with the right login:

== localhost:2587 StartTls, authenticate, trust dev certificate
   connected, TLS: True, capabilities: Authentication, EightBitMime, StartTLS, UTF8
   sent: Mail accepted

The default Timeout is two minutes:

Default SmtpClient.Timeout: 120000 ms

I set it lower in the tests that are expected to hang, so a wrong setting fails fast instead of blocking a request for two minutes.

Step 4: Pick SecureSocketOptions by Port

  • 587 (submission): connect in plain text, then upgrade with STARTTLS: SecureSocketOptions.StartTls.
  • 465 (implicit TLS): TLS from the first byte: SecureSocketOptions.SslOnConnect.
  • 25: meant for server-to-server relay; many cloud providers and ISPs block it for outgoing mail from apps.

SecureSocketOptions.Auto looks tempting, but in my tests it chose the mode from the port number, not from what the server does. On port 465 it used SSL on connect:

== localhost:465 Auto, trust dev certificate
   connected, TLS: True, capabilities: Authentication, EightBitMime, UTF8
   sent: Mail accepted

On the STARTTLS server on 2587 it connected in plain text and upgraded with STARTTLS:

== localhost:2587 Auto, authenticate, trust dev certificate
   connected, TLS: True, capabilities: Authentication, EightBitMime, StartTLS, UTF8
   sent: Mail accepted

But the implicit-TLS server on port 2465 (a non-standard port, common for internal relays and containers) got the STARTTLS treatment too, and the client waited for a plain-text greeting that never came:

== localhost:2465 Auto, trust dev certificate
   System.TimeoutException: Operation timed out after 10000 milliseconds
   inner: System.Threading.Tasks.TaskCanceledException: A task was canceled.

Set the option explicitly from configuration and the port number stops mattering.

The Errors I Hit

1. SslHandshakeException: Cannot determine the frame size

Use SslOnConnect against the STARTTLS port:

== localhost:2587 SslOnConnect
   MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection.

MailKit’s message then lists six possible reasons, starting with certificates, which sends people in the wrong direction. The inner exception is the real clue:

   inner: System.Security.Authentication.AuthenticationException: Cannot determine the frame size or a corrupted frame was received.

The client started a TLS handshake and the server answered with its plain-text SMTP greeting. That is reason 6 in MailKit’s list: “You are trying to connect to a port which does not support SSL/TLS.” Use StartTls on 587.

2. SslHandshakeException: certificate not trusted

Correct option, but the server uses a certificate the machine doesn’t trust (self-signed, or signed by a company CA that isn’t installed):

== localhost:2587 StartTls, authenticate
   MailKit.Security.SslHandshakeException: An error occurred while attempting to establish an SSL or TLS connection.

The server's SSL certificate could not be validated for the following reasons:
• The server certificate has the following errors:
  • A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.

   inner: System.Security.Authentication.AuthenticationException: The remote certificate was rejected by the provided RemoteCertificateValidationCallback.

In production the fix is to trust the certificate (install the CA) or connect to a host name that has a valid certificate. For a local test server, a validation callback that accepts exactly that certificate is fine:

        // Development only: accept the self-signed certificate of the local test server
        smtp.ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
            certificate?.Subject == "CN=localhost";

Don’t ship (s, c, h, e) => true: it accepts any certificate, including one from someone intercepting the connection, and then sends your SMTP password to them.

3. TimeoutException on an implicit-TLS port

The mirror image of error 1: None against port 465-style implicit TLS. The client waits for a greeting, the server waits for a TLS handshake:

== localhost:2465 None
   System.TimeoutException: Operation timed out after 10000 milliseconds
   inner: System.Threading.Tasks.TaskCanceledException: A task was canceled.

With the default timeout this hangs for two minutes. SslOnConnect fixes it.

4. The SMTP server does not support the STARTTLS extension

== localhost:2525 StartTls
   System.NotSupportedException: The SMTP server does not support the STARTTLS extension.

Real providers support STARTTLS; you see this with local test servers and old internal relays. StartTls refuses to continue without encryption, which is what you want in production. For a local server use None, or StartTlsWhenAvailable if the same code must work against both.

5. AuthenticationException: 535 Authentication failure

== localhost:2587 StartTls, authenticate, trust dev certificate
   connected, TLS: True, capabilities: Authentication, EightBitMime, StartTLS, UTF8
   MailKit.Security.AuthenticationException: 535: Authentication failure
   inner: MailKit.Net.Smtp.SmtpCommandException: Authentication failure

Against a real provider, a correct password can still fail here, because the account doesn’t allow password logins for SMTP. See the provider notes below before you reset anything.

6. Authentication is required

Connect, skip AuthenticateAsync, and send:

== localhost:2587 StartTls, trust dev certificate
   connected, TLS: True, capabilities: Authentication, EightBitMime, StartTLS, UTF8
   MailKit.ServiceNotAuthenticatedException: Authentication is required

Usually a configuration bug: the user name is empty in one environment, so the code skips the login.

7. No connection could be made because the target machine actively refused it

== localhost:2599 None
   System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it.

Nothing is listening on that host and port, or a firewall rejects the connection. If it works on your machine and fails on a server, check whether the hosting provider blocks outgoing SMTP ports.

Gmail, Outlook.com and Microsoft 365 Settings

I didn’t test against these accounts; the settings are from the providers’ help pages as of this update.

  • Gmail / Google Workspace: server smtp.gmail.com, ports 465 or 587 (Google’s SMTP settings). For apps that can’t sign in with OAuth, Google offers app passwords, which “can only be used with accounts that have 2-Step Verification turned on”; its own page now says they “aren’t recommended” and suggests “Sign in with Google” (OAuth) instead (Sign in with app passwords).
  • Outlook.com / Hotmail: server smtp-mail.outlook.com, port 587, STARTTLS, and the authentication method Microsoft lists is “OAuth2/Modern Auth”. The old smtp.live.com host from many tutorials (including the earlier version of this one) is not what Microsoft documents.
  • Microsoft 365 / Exchange Online: Microsoft is moving SMTP AUTH from basic authentication to OAuth 2.0 and has already disabled SMTP AUTH in tenants that weren’t using it (Authenticate an IMAP, POP or SMTP connection using OAuth).

MailKit supports OAuth 2.0 through SaslMechanismOAuth2, but getting the token is provider-specific, so I’ve left it out here rather than show untested code. For an app that sends a lot of email (order confirmations, password resets), a transactional email service with an SMTP relay or HTTP API is usually easier than a personal mailbox.

Checklist

  • Use MailKit.Net.Smtp.SmtpClient, not System.Net.Mail.SmtpClient.
  • 587 → StartTls, 465 → SslOnConnect; set the option explicitly, don’t rely on Auto for non-standard ports.
  • Read the inner exception of an SslHandshakeException: “frame size” means wrong TLS option, “not trusted” means certificate.
  • Never accept every certificate in production.
  • Lower Timeout in request paths so a wrong setting fails fast.
  • Send HTML with a text alternative (BodyBuilder does both).
  • Keep credentials in configuration or a secret store, and check whether the provider requires OAuth.
  • Test with a local server like smtp4dev before you point the app at a real mailbox.

Related: Dependency injection in C# · HttpClient in .NET 10 · ASP.NET Core Web API tutorial · all C# tutorials

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *