Send Email via Gmail

Sending email in .NET through Gmail

Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions.

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

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}

Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting.

  • If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on Signing in to Google > App passwords, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the fromPassword constant instead of your standard Gmail password.
  • If it is disabled, then you have to turn on Less secure app access, which is not recommended! So better enable the 2-Step verification.

C# sending email via Gmail account

If your Gmail account has 2-Step Verification enabled you will have to create an App-Specific Password to authenticate with instead.

Note also that SmtpClient is IDisposable - you should be putting it in a using (var smtpClient = new SmtpClient("smtp.gmail.com", 587)) { ... } block so that the SMTP connection RSETs, QUITs and closes correctly.

== edit ==

Also, it appears you have the from and recipients parameters switched around on smtpClient.Send.

string body = "<head>" +
"Here comes some logo" +
"</head>" +
"<body>" +
"<h1>Account confirmation reqest.</h1>" + Environment.NewLine +
"<a>Dear User, </a>" + Environment.NewLine +
"<a>In order to be able to use musicshop app properly, we require You to confirm Your email address.</a>" + Environment.NewLine +
"<a>This is the last step towards using our app.</a>" + Environment.NewLine +
"<a>Pleas follow this hyperlink to confirm your address.</a>" + Environment.NewLine +
"<a>[Callback url]</a>" +
"</body>";
try
{
using (var smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential()
{
UserName = Config.Username,
Password = Config.Password,
};
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;

//Oops: from/recipients switched around here...
//smtpClient.Send("targetemail@targetdomain.xyz", "myemail@gmail.com", "Account verification", body);
smtpClient.Send("myemail@gmail.com", "targetemail@targetdomain.xyz", "Account verification", body);
}
}
catch (Exception e)
{
Console.Error.WriteLine("{0}: {1}", e.ToString(), e.Message);
}

Sending email via GMail with app specific password

An application-specific password is simply a password that Gmail generates for you, and then you use it instead of your normal password (ie, in the TIdSMTP.Password property). This is explained in Gmail's documentation:

Sign in with App Passwords

How do I now (since June 2022) send an email via Gmail using a Python script?

Google has recently made changes to access of less secure apps (read here: https://myaccount.google.com/lesssecureapps).

In order to make your script work again, you'll need to make a new app password for it. Directions to do so are below:

  • Go to My Account in Gmail and click on Security.
    After that, scroll down to choose the Signing into Google option.
  • Now, click on App Password. (Note: You can see this option when two-step authentication is enabled). To enable two-step authentication:
    1. From the Signing into Google, click on the Two-step Verification option and then enter the password.
    2. Then Turn ON the two-step verification by entering the OTP code received on the mobile.

(Here's a quick link to the same page: https://myaccount.google.com/apppasswords)

  • Here, you can see a list of applications, choose the required one.
  • Next, pick the Select Device option and click on the device which is being used to operate Gmail.
  • Now, click on Generate.
  • After that, enter the Password shown in the Yellow bar.
  • Lastly, click on Done.

(Source: https://www.emailsupport.us/blog/gmail-smtp-not-working/)

Simply switch out the password the script is using for this newly generated app password. This worked for me and I wish the same for you.

I hope this helps!

What's solution for sending emails from python while gmail the less secure apps is not enabled anymore

If you want to continue using Gmail SMTP, you can set it up by setting an app password. An app password works like an alternate password for your account. It can only be used by the applications you share it with, so it’s more secure than sharing your primary password.

Here's how you can set it up: https://support.google.com/accounts/answer/185833?hl=en

How to send service emails via Gmail (machine-2-machine) with secure restrictions?

Lets start with send user account activation emails from my server I am gong to assume that you have a web app. This web app allows users to register with your system. Now when a user registers with your system you want to automatically send them an account creation email. Your idea is to use Google rather than setting up your own smtp server and sending these emails from your own system. Not a bad idea really.

Lets think about this for a minute the emails would need to be sent automatically so you need some kind of service sending them. To do that you want to use a service account. Again this is a great idea using a pre authorized service account that you will not need to have a user to authorize the app.

The only issue is that service accounts do not work with normal gmail accounts. To use a service account with Gmail api you need to use a google workspace domain account. The workspace domain admin would then be able to add permissions to the service account letting it act like a user on the domain. In this case your idea of no-reply.

So your workspace domain account would have a user called no-reply. The domain admin would then configure domain wide delegation to the service account allowing it to pretend that it is the user called no-reply. For all intensive purposes the service account is the no-reply user. It will be able to send mails as if they are coming from that user.

For all this to work you will need the workspace account with that user.

Have a look at the following link, it's actually one of Google's better examples it shows how to set up the delegation.

Perform Google Workspace Domain-Wide Delegation of Authority

Here you create a service account with credentials, allow this account to impersonate other users (e.g. the no-reply user), to only use the Gmail API and to only use it to send emails.

  • the documentation is a bit outdated, you can skip the step Grant users access to this service account and create the service account key afterwards via the service account edit function: Manage keys
  • in the step Domain wide delegation you need Google Admin not the Google Cloud Platform Admin Console as in the previous step

Just remember to swap out the lines about

https://www.googleapis.com/auth/admin.directory.user,
https://www.googleapis.com/auth/admin.directory.group

and use

https://www.googleapis.com/auth/gmail.send

instead as you want to access the Gmail API and only allow the service account to send (not read) emails

tip

in the sample code in that link

.setServiceAccountUser(userEmail)

userEmail is the email address of the user you want to impersonate in this case no-reply@x.y

So I guess what I am saying is that what you want to do is definitely possible, however, it may be easier just to set up your own SMTP server.

Gmail email send c#

Try formatting the message as I have here. and use Authenticate instead of NetworkCredential.

using MailKit.Net.Smtp;
using MimeKit;

Console.WriteLine("Hello, World!");

var message = new EmailMessage()
{
From = "xxxxx@gmail.com",
To = "xxx1@gmail.com",
MessageText = "test",
Subject = "test"
};

try
{
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 465, true);
client.Authenticate(message.From, "AppsPassword");
client.Send(message.GetMessage());
client.Disconnect(true);
}


}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

public class EmailMessage
{
public string To { get; set; }
public string From { get; set; }
public string Subject { get; set; }
public string MessageText { get; set; }

public MimeMessage GetMessage()
{
var body = MessageText;
var message = new MimeMessage();
message.From.Add(new MailboxAddress("test", From));
message.To.Add(new MailboxAddress("test", To));
message.Subject = Subject;
message.Body = new TextPart("plain") { Text = body };
return message;
}
}

How to send an email using python after Google's policy update on not allowing just username and password?

Here is a more precise answer with all the main steps. I hope it will help other people.

  1. Log in into your email account: https://myaccount.google.com

  2. Then go to the security part

Sample Image

Be sure that you have turn on two steps verification and click on "App password"

Sample Image


  1. After select email and the corresponding device

Sample Image


  1. It will generate a password that will look like this; it is this password that you have to use in your python script.

Sample Image


  1. This password will appear here; in this place, you will have the option to erase it (so it will be no longer be useful to connect to your email account).

Sample Image

Hope it will help other people!

Gmail SMTP server stopped working as it no longer support Less Secure Apps

Yes, It's not working after removing the option by google. But nothing to worry! It's still very simple to send email. To send email again you need to do this as bellow:

  1. Login to your gmail
  2. Go to Security setting and Enable 2 factor authentication
  3. After enabling this you can see app passwords option. Click here!
  4. And then, from Your app passwords tab select Other option and put your app name and click GENERATE button to get new app password.
  5. Finally copy the 16 digit of password and click done. Now use this password instead of email password to send mail via your app.

Now you can use just email and this generated pass to send email.



Related Topics



Leave a reply



Submit