Skip to content

Obscure Problems and Gotchas

If you couldn't find your answer to your weird problem, you might find it here.

  • About
  • Application Errors Hall of Shame
  • DyslexicApps
C#, Development, How to, Obscure

Introduction

When you search for this on google you will find one hundred million results that all pretty much say exactly the same thing. The problem is none of them are from a developer’s perspective (from what I can tell) therefore none of the articles explained what was needed to make it work with the C# System.Net.Mail.SmtpClient class. After a lot of trial and error with frustration sprinkled in, I figured it out. Unfortunately, I am not 100% sure what combination of things I did made everything work.

Setup your Google account security first

Nothing works unless you have setup your account security correctly. There are some older articles that indicate a flag in your account about enabling “Unsafe applications” – skip this and enable two-factor authentication (2FA) on your account instead. The reason you need 2FA is so you can create an application password instead.

  1. Go to https://myaccount.google.com/
  2. On the left-hand side of the page locate the “Security” link.
  3. Under the “Signing in to Google” section go through the motions of enabling 2FA – I won’t explain that here. When 2FA is enabled go on to the next step.
  4. After 2FA is enabled you will see “App passwords” shows up in the “Signing in to Google” section under 2FA.
  5. Fill out the form – really it doesn’t matter how you do this but for the sake of argument:
    1. For the “Select app” drop down select “Other”
    2. Enter whatever meaningful name you want
    3. For the “Select device” drop down select “Windows Computer”
    4. Click the “GENERATE” button
    5. Copy the password
      1. Note: Even though it presents with spaces, it won’t have spaces after you copy it.
  6. Keep your password handy for the next part

Gmail settings

In order for this to work correctly you now need to enable POP and IMAP access. I will be perfectly honest; this is where I got confused I enabled both because I was annoyed at this point with not knowing why none of this was working.

  1. Go to https://mail.google.com and access your settings
  2. Click on the “Forwarding and POP/IMAP” section
    1. Enable POP
      1. Fill this section out however you want as long as it is enabled
    2. Enable IMAP
      1. Fill this section out however you want as long as it is enabled

SMTP settings

Reminder, these instructions are for sending an email using Gmail’s SMTP settings specifically for use with the System.Net.Mail.SmtpClient.

PropertyValue
DeliveryMethodSmtpDeliveryMethod.Network
Hostsmtp.gmail.com
Port587
EnableSsltrue
UseDefaultCredentialstrue
CredentialsLook below for more details
I have a code example below

Credentials

I could not find a straight forward answer on what the user name is supposed to be when using app passwords. It is safe to say it is the same username of the account and I have tested this, it works just fine. I just wanted written instructions that say this clearly. It’s only hinted at.

For the “Credentials” property you need to use a “System.Net.NetworkCredential” object and populate using the second constructor which takes two strings:

ArgumentValue description
userNameYour gmail account email address in the form: “[email protected]”
passwordThe application password generated up top
Be very careful where you enter this information. It gives anyone access to your account!

Code example

I use LinqPad for doing quick modeling of things. This was created using LinqPad and I have provided the raw format of that file so namespaces are included:

<Query Kind="Program">
  <Namespace>System.Net.Mail</Namespace>
  <Namespace>System.Net</Namespace>
</Query>

void Main()
{
	SendViaGmail(new Email());
}

public void SendViaGmail(Email email)
{
	using (var client = new SmtpClient())
	{
		client.DeliveryMethod = SmtpDeliveryMethod.Network;
		client.Host = "smtp.gmail.com";
		client.Port = 587; //SSL 465, TLS: 587 - TLS is what worked
		client.EnableSsl = true;
		client.UseDefaultCredentials = true;
		client.Credentials = new NetworkCredential("[email protected]", "TheAppPasswordYouGenerated");
		
		using (var mail = new MailMessage(email.From, email.To))
		{
			mail.Subject = email.Subject;
			mail.Body = email.Message;
			mail.IsBodyHtml = true;
			
			client.Send(mail);

			Console.WriteLine($"{email.To}, {email.Subject}, {mail.Body}");
		}
	}
}

public class Email
{
	public const string StockSubject = "This is a test email";

	public string From { get; set; } = @"[email protected]";

	public string To { get; set; } = @"[email protected]";

	public string Subject { get; set; } = StockSubject;

	public string Message { get; set; } = @"<html><span>This is a test heading</span></html>";
}

The thing that really got me screwed up for a while was trying to figure out which port to use. I kept trying to use SSL 465 when it turned out to be TLS 587 that worked. I’m still confused as to why SSL 465 didn’t work.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)

Related

by: admin2020-07-26
accountappapplicationC#emailfreegmailnotpasswordsendsmtpSmtpClientssltlsworking

Post navigation

Offline installation of Microsoft Machine Learning server components SQL 2019 is stuck
Biases in naming database objects

Search posts

Happy find? Help me buy the coffee that fuels these articles!

Like what you are reading?

It takes time to write these quality blog posts and sometimes software. Maybe something I have written has benefited you? Blog posts can take anywhere from a few minutes, to a couple of hours, to several days to construct. Software is a constant work in progress. Want to help me buy my next bag of coffee?

Anything is appreciated

Categories

Recent Comments

  • Unable to connect to database with .NET Core 3.1 File System Publish to IIS on DotNet Core EF migration not working
  • Oceane on Offline installation of Microsoft Machine Learning server components SQL 2019 is stuck
  • admin on Offline installation of Microsoft Machine Learning server components SQL 2019 is stuck
  • Chris on Offline installation of Microsoft Machine Learning server components SQL 2019 is stuck
  • admin on Offline installation of Microsoft Machine Learning server components SQL 2019 is stuck

Archives

Search posts

Search posts

SSL Secure

Copyright © All rights reserved. Theme Creativ Mag by Creativ Themes