Send Emails in ASP.NET Core 5 Using Gmail API

We can send emails using Gmail API with a simple configuration in our ASP.NET Core web API Project. In this tutorial, you will learn and practice how to Send Emails in ASP.NET Core 5 Using Gmail API.

If you have not created your ASP.NET Core Multi-tier web project please follow this link.

Tools:

Follow these simple steps to configure Gmail API to send emails:

First of all, we have to create a project on Console.cloud.google.com.

To create your project open console.cloud.google.com

on the top bar click on the drop-down and click on create a project.

Send Emails in ASP.NET

After Clicking on this you will get something like the below image, fill name of your project and click on create a project.

Send Emails in ASP.NET

On the Dashboard of your project click enable API and Services

Send Emails in ASP.NET

Now select Gmail API.

Send Emails in ASP.NET

After enable API and you will get this Page. Now click on create credentials.

Send Emails in ASP.NET

After clicking on create credentials click select Gmail API

Send Emails in ASP.NET

Select Gmail API and click on next. After filling in your required information click on save and continue.

Send Emails in ASP.NET

Now again just click on save and continue.

Send Emails in ASP.NET

After that, you will get OAuth Client ID. Fill the fields accordingly and do not forget to add your localhost URL. After filling the data, Click on create.

Send Emails in ASP.NET

Now you will have your credentials. Download the credentials and click on the Done button.

Send Emails in ASP.NET

Also do not forget to publish your google App.

Send Emails in ASP.NET

Install this npm Package into your ASP.NET Core project.

  • Google.Apis.Gmail.V1

Now you have to put that credentials JSON file into your project. so after putting that Json file, we will use those credentials into our Email sending method.

Send Emails in ASP.NET

After this, we will implement our email sending service class. Here is the code.

using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using mhparks_model.Models;
using Multi_tier_Data.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Multi_tier_Services.EmailService
{
    public class EmailServices: IEmailService
    {
        private readonly ApplicationDbContext _context;
        public EmailServices(ApplicationDbContext context)
        {
            _context = context;
        }
        public bool SendEmail(EmailTemplate data)
        {
            try
            {
                string[] Scopes = { GmailService.Scope.GmailSend };
                UserCredential credential;
                using (var stream = new FileStream(
                    "./client_secret.json",
                    FileMode.Open,
                    FileAccess.Read
                ))
                {
                    string credPath = "token_Send.json";
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                                 GoogleClientSecrets.FromStream(stream).Secrets,
                                  Scopes,
                                  "user",
                                  CancellationToken.None,
                                  new FileDataStore(credPath, true)).Result;
                    //Console.WriteLine("Credential file saved to: " + credPath);
                }
                // Create Gmail API service.
                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "mycodebit",
                });
                //Parsing HTML 
                string message = $"To: {data.To}\r\nSubject: {data.Subject}\r\nContent-Type: text/html;charset=utf-8\r\n\r\n{data.Body}";
                var newMsg = new Google.Apis.Gmail.v1.Data.Message();
                newMsg.Raw = this.Base64UrlEncode(message.ToString());
                Message response = service.Users.Messages.Send(newMsg, "me").Execute();

                if (response != null)
                    return true;
                else
                    return false;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        private string Base64UrlEncode(string input)
        {
            var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
            // Special "url-safe" base64 encode.
            return Convert.ToBase64String(inputBytes)
              .Replace('+', '-')
              .Replace('/', '_')
              .Replace("=", "");
        }
    }
}

After this, we will call our email service through API.

Send Emails in ASP.NET

After hitting this API with the data you will get a Google Sign-in form. Login with the same google account that you have used to create an account on cloud.google.com.

Send Emails in ASP.NET

Click on your google account. Now you will have this screen.

Send Emails in ASP.NET

After Clicking on Advance click on Go to unsafe.

Send Emails in ASP.NET

Now continue your access after checking the checkbox to send emails.

Send Emails in ASP.NET

After the continue, you will receive your first email.

Send Emails in ASP.NET

This Authentication is for one time after this first authentication whenever you will call this API or service for sending the email, an email will be sent successfully.

You can also see that google also has placed a token into your project after one-time authentication now this token will be used for authentication purposes.

Send Emails in ASP.NET

I have discussed dependency injection in C# with code examples for beginners. Visit this post.

Conclusion:

You can configure Gmail API by following these simple steps that we have mentioned above and can use for email confirmation of your users, notifications, and reset the password if you face any issue or problem while configuring Gmail API with your ASP.NET Core project feel free to comment below. We will try to respond ASAP.

Leave a Reply

Your email address will not be published.