Dashboard Shop Ask a question
Log in
Knowledge base

Sending Email via Google Workspace (Gmail) using C#

If you prefer to relay email through Google servers (Gmail or Google Workspace) instead of using our local mail server, you can use the standard .NET SmtpClient class. This ensures high deliverability but requires specific security settings on your Google account.

Crucial Prerequisite: App Passwords

Google no longer supports using your standard account password for third-party applications. To use the code below, you must:

  1. Enable 2-Step Verification on your Google Account.
  2. Go to your Google Security settings and generate an App Password.
  3. Use that 16-character App Password in the script below instead of your regular email password.

C# Code Example

The following code connects to Google's SMTP server using Port 587 (STARTTLS). Copy and adapt this into your code-behind or controller:

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

// Configuration
string gmailAddress = "your.name@gmail.com"; // Your full Gmail address
string gmailAppPassword = "xxxx xxxx xxxx xxxx"; // Your 16-char App Password
string toAddress = "recipient@external.com";

// Setup the client
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true; // Gmail requires SSL/TLS
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(gmailAddress, gmailAppPassword);

// Create the message
MailMessage msg = new MailMessage();
msg.From = new MailAddress(gmailAddress);
msg.To.Add(toAddress);
msg.Subject = "Test from C# and Gmail";
msg.Body = "<h1>This is a test email</h1><p>Sent via Google SMTP</p>";
msg.IsBodyHtml = true;

try
{
    client.Send(msg);
    // Success logic here (e.g., Response.Write("Email sent!"))
}
catch (Exception ex)
{
    // Error logic here
    // Response.Write("Error: " + ex.Message);
}

Troubleshooting

  • Authentication Failed: If you receive an authentication error, double-check that you are using an App Password, not your login password.
  • Port Settings: The System.Net.Mail library works best with Gmail on Port 587 with EnableSsl = true. Do not use Port 465, as that uses a different SSL protocol not natively supported by the older SmtpClient class without additional configuration.
© Copyright 2026 Doka management panel