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.
Google no longer supports using your standard account password for third-party applications. To use the code below, you must:
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);
}
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.