Send Mail Using OAuth 2.0 In .Net Core 6.0 Part 2

In this article, we are going to learn how to send mail using OAuth credentials in .Net Core 6.0.

To get the OAuth credentials first follow Part-1.

Prerequisites

Let us understand with the help of an example.

First, open Visual Studio 2022 and create a .NET 6.0 application by clicking Create a new project.

Then install the following packages.

  • Google APIs Core Client Library
  • Google APIs Client Library
  • Google APIs Auth Client Library
  • Google.Apis.Oauth2.v2 Client Library
  • MimeKit

Note:System.Net.Mail does not support OAuth or OAuth2. However, you can use MailKit’s or IMAP To Send Mail(MailKit’s only supports OAuth2).

Create a new SendMailController in the Controller folder and paste the below code into it.

using Google.Apis.Auth.OAuth2;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.AspNetCore.Mvc;
using MimeKit;
using MimeKit.Text;

namespace SendMailDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MailController : ControllerBase
    {
        [HttpPost("SendMail")]
        public async Task<IActionResult> SendMail(string emailId)
        {
            try
            {
                string clientId = "Your Client Id";
                string clientSecret = "Your Client Secret Key";
                string fromMail = "Your Register Email Id";
                string[] scopes = new string[] { "https://mail.google.com/" };
                ClientSecrets clientSecrets = new()
                {
                    ClientId = clientId,
                    ClientSecret = clientSecret
                };
                //Requesting authorization
                UserCredential userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, scopes, "user", CancellationToken.None).Result;
                //Authorization granted or not required (if the saved access token already available)
                if (userCredential.Token.IsExpired(userCredential.Flow.Clock))
                {
                    //The access token has expired, refreshing it
                    if (!userCredential.RefreshTokenAsync(CancellationToken.None).Result)
                    {
                        return StatusCode(500);
                    }
                }
                var email = new MimeMessage();
                email.From.Add(MailboxAddress.Parse(fromMail));
                email.To.Add(MailboxAddress.Parse(emailId));
                email.Subject = "Sending Email Using OAuth Net 6.0";
                email.Body = new TextPart(TextFormat.Html) { Text = "<h3>Mail Body</h3>" };

                using (var client = new SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
                    var oauth2 = new SaslMechanismOAuth2(fromMail, userCredential.Token.AccessToken);
                    client.Authenticate(oauth2);

                    await client.SendAsync(email);
                    client.Disconnect(true);
                }
                return Ok();
            }
            catch (Exception ex)
            {
                return StatusCode(500);
            }
        }
    }
}

That’s It.

Now let’s run your project and add the email address where you want to send mail.

Now you can check Gmail where you send mail.

Also check, Generate PDF Using Rotative In .NET Core

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories