Barış Kısır

Automated Communication: Sending Emails via SMTP in .NET

22 Mar 2017

Establishing Programmatic Email Pipelines

Implementing an automated email notification system is a ubiquitous requirement in modern software, ranging from user registration confirmations to system alerts. While many enterprise applications now pivot toward API-based providers (like SendGrid or Mailgun), the standard SmtpClient class within the .NET Framework remains a viable option for simpler integrations.

Security Prerequisites

When utilizing personal Gmail accounts for development purposes, it was historically necessary to enable “Less secure app access.” However, in modern security contexts, App Passwords or OAuth2 authentication are the mandated standards to ensure account integrity.

Implementation Strategy: SMTP Configuration

The following implementation demonstrates the configuration required to orchestrate an email transmission through Gmail’s SMTP servers.

using System.Net;
using System.Net.Mail;

public static void DispatchEmail(string recipientAddress, string emailSubject, string emailBody)
{
    var senderAddress = new MailAddress("[email protected]", "System Automator");
    var recipient = new MailAddress(recipientAddress);
    const string credentialsToken = "your-app-specific-password";

    using (var smtpGate = new SmtpClient())
    {
        smtpGate.Host = "smtp.gmail.com";
        smtpGate.Port = 587; // Utilizing TLS for secure transmission
        smtpGate.EnableSsl = true;
        smtpGate.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpGate.UseDefaultCredentials = false;
        smtpGate.Credentials = new NetworkCredential(senderAddress.Address, credentialsToken);
        smtpGate.Timeout = 20000;

        using (var mailPayload = new MailMessage(senderAddress, recipient))
        {
            mailPayload.Subject = emailSubject;
            mailPayload.Body = emailBody;
            mailPayload.IsBodyHtml = true; // Support for HTML-enriched content

            smtpGate.Send(mailPayload);
        }
    }
}

Key Architectural Considerations

  1. Asynchronous Transmission: For performance-critical applications, utilize SendMailAsync to prevent the calling thread from blocking during the network handshake.
  2. Resilience and Retries: Implement a robust retry mechanism to handle transient network disruptions.
  3. Modern Alternatives: For high-volume production environments, consider migrating to REST-based email services which offer superior deliverability reporting and enhanced security over standard SMTP.

Research the Source: The complete implementation logic and configuration samples are available on GitHub.