SMTP and OAuth 2
System.Net.Mail does not support OAuth or OAuth2. However, you can use MailKit's (note: only supports OAuth2) SmtpClient to send messages as long as you have the user's OAuth access token (MailKit does not have code that will fetch the OAuth token, but it can use it if you have 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 ("your-developer-id@developer.gserviceaccount.com") {
// Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes
Scopes = new[] { "https://mail.google.com/" },
User = "username@gmail.com"
}.FromCertificate (certificate));
bool result = await credential.RequestAccessTokenAsync (CancellationToken.None);
// 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 ("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
// use the access token
var oauth2 = new SaslMechanismOAuth2 ("username@gmail.com", credential.Token.AccessToken);
client.Authenticate (oauth2);
client.Send (message);
client.Disconnect (true);
}
Sending email with OAUTH2 and smtp.gmail (C#)
Im a little confused as to what it is you are trying to do. You say you want to send an email using the SMTP server yet you are connecting to the gmail api. Why not just send your emails via the gmail api then?
Assuming you have just gone in the wrong direction. You should know that the SmtpClient can handle the client from the google .Net client library directly. Just let it get its access token when needed.
await client.AuthenticateAsync (oauth2, CancellationToken.None);
If all you want to do is send an email from the smtp server. Try the following sample.
Full sample
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
var to = "test@Gmail.com";
var from = "test@gmail.com";
var path = @"C:\YouTube\dev\credentials.json";
var scopes = new[] { "https://mail.google.com/" };
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromFile(path).Secrets,
scopes,
"GmalSmtpUser",
CancellationToken.None,
new FileDataStore(Directory.GetCurrentDirectory(), true)).Result;
var message = new EmailMessage()
{
From = from,
To = to,
MessageText = "This is a test message using https://developers.google.com/gmail/imap/xoauth2-protocol",
Subject = "Testing GmailSMTP with XOauth2"
};
try
{
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 465, true);
var oauth2 = new SaslMechanismOAuth2 (message.From, credential.Token.AccessToken);
await client.AuthenticateAsync (oauth2, CancellationToken.None);
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("From a user", From));
message.To.Add(new MailboxAddress("To a user", To));
message.Subject = Subject;
message.Body = new TextPart("plain") { Text = body };
return message;
}
}
GMail API / OAUTH2 - How To Send Emails With Traditional C# SMTP Method Being Deprecated?
Go to your google account and create an apps password once this is created just use that instead of the actual password for your gmail account.
Security
// C# code
using (SmtpClient smtpClient = new SmtpClient(SmtpDomain, SmtpPortNumber))
{
smtpClient.DeliveryMethod = SmtpDeliveryMethod;
smtpClient.UseDefaultCredentials = UseDefaultCredentials;
smtpClient.EnableSsl = true;
smtpClient.Credentials = new NetworkCredential(SmtpUsername, appsPasswrod);
MailMessage mailMessage = new MailMessage { /* ... */ };
smtpClient.Send(mailMessage);
}
Related Topics
Get String Name of Property Using Reflection
Can a Picturebox Show Animated Gif in Windows Application
Generating a Random Decimal in C#
Why Is This Process Crashing as Soon as It Is Launched
How to Drag a Usercontrol Inside a Canvas
How to Create an Instance from a String in C#
How to Get the Subscribers of an Event
No Database Provider Has Been Configured for This Dbcontext' on Signinmanager.Passwordsigninasync
C# How to Loop User Input Until the Datatype of the Input Is Correct
How to Use Datareceived Event of the Serialport Port Object in C#
Closing a File After File.Create
Why Does Guid.Tobytearray() Order the Bytes the Way It Does
How to Detect the Original MAC Address After It Has Been Spoofed
Linq Query Group by and Selecting First Items