Sending Emails with SMTP in C# / .NET

Send emails through AhaSend’s SMTP servers using C# and .NET with the powerful MailKit library. This guide covers why you should avoid System.Net.Mail and use MailKit instead for reliable email delivery.
Avoid System.Net.Mail: The built-in SmtpClient in .NET does not reliably support AUTH PLAIN over STARTTLS, causing authentication failures with AhaSend. Use MailKit instead for guaranteed compatibility.

Prerequisites

Before you begin, ensure you have:
Need SMTP Credentials? If you haven’t created SMTP credentials yet, check out our SMTP Credentials guide for step-by-step instructions.

Why MailKit Over System.Net.Mail?

AhaSend works with any SMTP-compatible library, but for C#/.NET applications, we strongly recommend MailKit over the built-in System.Net.Mail:

✅ MailKit (Recommended)

Pros: Modern, reliable STARTTLS
Auth: AUTH PLAIN/LOGIN support
Compatibility: Works with StartTLS
Features: Rich MIME support, attachments, HTML

❌ System.Net.Mail (Avoid)

Issues: Unreliable STARTTLS authentication
Auth: Silent AUTH failures with AhaSend
Status: Legacy, minimal updates
Problems: May not send AUTH commands at all

Connection Settings

Use these settings for all C#/.NET SMTP configurations with AhaSend:

Primary Server

Host: send.ahasend.com
Ports: 587 (recommended), 25, 2525
Security: STARTTLS
Authentication: Required

US Server

Host: send-us.ahasend.com
Ports: 587 (recommended), 25, 2525
Security: STARTTLS
Authentication: Required

❌ Why System.Net.Mail Fails

The built-in System.Net.Mail.SmtpClient in .NET has fundamental issues with STARTTLS authentication that make it incompatible with AhaSend.

The Problem

Even with correct credentials and EnableSsl = true, the SMTP client often never issues an AUTH command after the STARTTLS handshake. This causes silent authentication failures where the connection appears to succeed but emails are rejected.
Tested and Confirmed: We’ve tested this issue on .NET 9 across Linux and Windows. The problem persists across different .NET versions and platforms.

What Doesn’t Work

Here’s the problematic code that fails with AhaSend:
System.Net.Mail (Don't Use This)
using System;
using System.Net;
using System.Net.Mail;

class Program
{
    static void Main(string[] args)
    {
        SmtpClient smtp = new SmtpClient("send.ahasend.com", 587);

        // Enable StartTLS
        smtp.EnableSsl = true;

        // Don't use the OS/Windows account. We want to supply our own credentials.
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential("YOUR_SMTP_USERNAME", "YOUR_SMTP_PASSWORD");

        MailMessage message = new MailMessage("[email protected]", "[email protected]");
        message.Subject = "Testing Auth";
        message.Body = "This is a test email via AUTH PLAIN.";

        try
        {
            smtp.Send(message);
            Console.WriteLine("Email sent successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error sending email: " + ex.Message);
            if (ex.InnerException != null)
            {
                Console.WriteLine("Inner Exception: " + ex.InnerException.Message);
            }
        }
    }
}

Debugging the Issue

You can confirm this authentication failure by capturing SMTP traffic with tools like tcpdump or Wireshark:
  1. Connection succeeds - Client connects to AhaSend SMTP server
  2. STARTTLS works - TLS encryption is established successfully
  3. AUTH command missing - Client never sends authentication credentials
  4. Silent failure - No clear error message, just rejection
Know a Workaround? If you’ve found a way to make System.Net.Mail work reliably with AhaSend’s AUTH PLAIN over STARTTLS, please contact our support team. We’d be happy to update this guide with your solution!
MailKit is a modern, actively maintained .NET library that correctly handles SMTP authentication with AhaSend. It properly negotiates authentication mechanisms like PLAIN and LOGIN over STARTTLS.

Installation

Install MailKit via NuGet Package Manager:
Install-Package MailKit
MimeKit Included: MailKit automatically includes MimeKit for MIME message construction. No additional packages needed!

Basic MailKit Examples

using System;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;

class Program
{
    static void Main()
    {
        using (var client = new SmtpClient())
        {
            try
            {
                // Connect to AhaSend SMTP with STARTTLS
                client.Connect("send.ahasend.com", 587, SecureSocketOptions.StartTls);

                // Authenticate with your SMTP credentials
                client.Authenticate("YOUR_SMTP_USERNAME", "YOUR_SMTP_PASSWORD");

                // Create a simple message
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Your Company", "[email protected]"));
                message.To.Add(new MailboxAddress("User", "[email protected]"));
                message.Subject = "Welcome to our platform!";
                message.Body = new TextPart("plain")
                {
                    Text = "Thanks for signing up. We're excited to have you!"
                };

                client.Send(message);
                client.Disconnect(true);

                Console.WriteLine("Email sent successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to send email: {ex.Message}");
            }
        }
    }
}

Advanced MailKit Examples

using System;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;

class Program
{
    static void Main()
    {
        using (var client = new SmtpClient())
        {
            try
            {
                // Connect to AhaSend SMTP with STARTTLS
                client.Connect("send.ahasend.com", 587, SecureSocketOptions.StartTls);

                // Authenticate with your SMTP credentials
                client.Authenticate("YOUR_SMTP_USERNAME", "YOUR_SMTP_PASSWORD");

                // Create message with multiple recipients
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Your Company", "[email protected]"));

                // Add multiple recipients
                message.To.Add(new MailboxAddress("User One", "[email protected]"));
                message.To.Add(new MailboxAddress("User Two", "[email protected]"));

                // Add CC recipient
                message.Cc.Add(new MailboxAddress("Manager", "[email protected]"));

                // Add BCC recipient (not visible to other recipients)
                message.Bcc.Add(new MailboxAddress("Analytics", "[email protected]"));

                message.Subject = "Product Updates with Tracking";

                // Add AhaSend special headers
                message.Headers.Add("ahasend-track-opens", "true");
                message.Headers.Add("ahasend-track-clicks", "true");
                message.Headers.Add("ahasend-tags", "product-update,newsletter,csharp");
                message.Headers.Add("ahasend-message-retention", "30");
                message.Headers.Add("ahasend-message-data-retention", "7");

                var builder = new BodyBuilder();
                builder.TextBody = "Check out our latest features at https://yourdomain.com/features";
                builder.HtmlBody = @"
                    <html>
                    <body>
                        <h1>Product Updates</h1>
                        <p>Check out our <a href=""https://yourdomain.com/features"">latest features</a>!</p>
                        <p>This email has tracking enabled and custom tags.</p>
                    </body>
                    </html>";

                message.Body = builder.ToMessageBody();

                client.Send(message);
                client.Disconnect(true);

                Console.WriteLine("Email sent with special headers!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to send email: {ex.Message}");
            }
        }
    }
}

Testing with Sandbox Mode

Use sandbox mode to safely test your C# email integration:
using System;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;

class Program
{
    static void Main()
    {
        using (var client = new SmtpClient())
        {
            try
            {
                // Connect to AhaSend SMTP with STARTTLS
                client.Connect("send.ahasend.com", 587, SecureSocketOptions.StartTls);

                // Authenticate with your SMTP credentials
                client.Authenticate("YOUR_SMTP_USERNAME", "YOUR_SMTP_PASSWORD");

                // Create sandbox test message
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Test", "[email protected]"));
                message.To.Add(new MailboxAddress("Test User", "[email protected]"));
                message.Subject = "Sandbox Test Email";

                // Enable sandbox mode
                message.Headers.Add("AhaSend-Sandbox", "true");
                message.Headers.Add("AhaSend-Sandbox-Result", "deliver");

                message.Body = new TextPart("plain")
                {
                    Text = "This email is sent in sandbox mode for testing."
                };

                client.Send(message);
                client.Disconnect(true);

                Console.WriteLine("Sandbox email sent successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to send sandbox email: {ex.Message}");
            }
        }
    }
}
Sandbox Benefits: Emails sent in sandbox mode are free, trigger webhooks normally, and never actually deliver to recipients - perfect for development and testing.

Resources

Pro Tip: Always use MailKit instead of System.Net.Mail for AhaSend integration. Configure your SMTP settings through dependency injection, implement proper error handling with retry logic, and start with sandbox mode during development. Use async patterns for better performance in web applications.