Solving common problems when sending an email using the Gmail SMTP server
Sending an email using the Google Gmail SMTP server is not as simple as you would expect. For example, you have to authenticate to the Gmail SMTP server to send an email, but you cannot use the same password that you are using for logging into the Gmail web application.
The following article shows some of the most common problems you may encounter and offers guidance on how to solve them.
The sample code uses the Rebex SMTP library (also part of the Rebex Mail Pack.
Wrong: Using an unencrypted communication channel
var smtp = new Rebex.Net.Smtp();
// This WILL NOT WORK because Gmail requires TLS
smtp.Connect("smtp.gmail.com");
smtp.Send(from: "example@gmail.com", to: "test@example.com", subject: "test email", body: "Hi!");
smtp.Disconnect();
Will throw an error like this:
Must issue a STARTTLS command first. w10-20020a05600c474a00b003b435c41103sm6476362wmo.0 - gsmtp (530).
Solution: Make sure to use TLS encryption, as shown in Sending an email using the Gmail SMTP server in C#.
Wrong: Using non-authenticated SMTP
Try to run the following code:
var smtp = new Rebex.Net.Smtp();
// This WILL NOT WORK because Gmail requires authentication
smtp.Connect("smtp.gmail.com", SslMode.Implicit);
smtp.Send(from: "example@gmail.com", to: "test@example.com", subject: "test email", body: "Hi!");
smtp.Disconnect();
And you'll get an error such as this one:
https://support.google.com/mail/?p=WantAuthError m16-20020a05600c3b1000b003cfd0bd8c0asm1469797wms.30 - gsmtp (530).
Solution: Authenticate before sending the email, as shown in Sending an email using Gmail SMTP server in C#.
Wrong: Using your Google account password for authentication
var smtp = new Rebex.Net.Smtp();
smtp.Connect("smtp.gmail.com", SslMode.Implicit);
// This WILL NOT WORK because Gmail does not allow using the main Google account password for SMTP authentication.
// You should use an App Password or OAuth 2.0 instead.
smtp.Login("example@gmail.com", "gmail password");
smtp.Send(from: "example@gmail.com", to: "test@example.com", subject: "test email", body: "Hi!");
smtp.Disconnect();
Will end with this error:
https://support.google.com/mail/?p=InvalidSecondFactor m1-20020a05600c4f4100b003b4fe03c881sm5182825wmq.48 - gsmtp (534)
There are two solutions to this:
- Generate an App Password and use it instead of your main Google password. Keep using the same code.
- Use OAuth 2.0. This is more secure but requires slightly more complex code.
Both these approaches are demonstrated in Sending an email using the Gmail SMTP server in C# article, which includes sample code as well.