Anatoly Anatoly - 9 months ago 456
C# Question

How to send email by using MailKit?

According to the new google politics I can't sent an email. "Less secure apps" are considered for google the application which don't use OAuth 2.0.

I would like to use MailKit to solve this problem

var message = new MimeMessage();

message.From.Add(new MailboxAddress("Joey Tribbiani", ""));
message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", ""));
message.Subject = "How you doin'?";
message.Body = new TextPart("plain"){ Text = @"Hey" };

using (var client = new SmtpClient())
client.Connect("", 587);

////Note: only needed if the SMTP server requires authentication
client.Authenticate("", "mypassword");


But I have got
An exception of type 'MailKit.Security.AuthenticationException' occurred in MailKit.dll but was not handled in user code.Additional information: Authentication failed.

I don't want to change my security settings. Because I want that everything will be secure. That's why I start to use MailKit rather than System.Net.Mail

How can I fix it?


The first thing you need to do is follow Google's instructions for obtaining OAuth 2.0 credentials for your application.

Once you've done that, the easiest way to obtain an access token is to use Google's Google.Apis.Auth library:

var certificate = new X509Certificate2 (@"C:\path\to\certificate.p12", "password", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential (new ServiceAccountCredential
    .Initializer ("") {
    // Note: other scopes can be found here:
    Scopes = new[] { "" },
    User = ""
}.FromCertificate (certificate));

//You can also use FromPrivateKey(privateKey) where privateKey
// is the value of the fiel 'private_key' in your serviceName.json file

bool result = await credential.RequestAccessTokenAsync (cancel.Token);

// Note: result will be true if the access token was received successfully

Now that you have an access token (credential.Token.AccessToken), you can use it with MailKit as if it were the password:

using (var client = new SmtpClient ()) {
   client.Connect ("", 587);

   // use the OAuth2.0 access token obtained above as the password
   client.Authenticate ("", credential.Token.AccessToken);

   client.Send (message);
   client.Disconnect (true);