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.
After Clicking on this you will get something like the below image, fill name of your project and click on create a project.
On the Dashboard of your project click enable API and Services
Now select Gmail API.
After enable API and you will get this Page. Now click on create credentials.
After clicking on create credentials click select Gmail API
Select Gmail API and click on next. After filling in your required information click on save and continue.
Now again just click on save and continue.
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.
Now you will have your credentials. Download the credentials and click on the Done button.
Also do not forget to publish your google App.
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.
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.
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.
Click on your google account. Now you will have this screen.
After Clicking on Advance click on Go to unsafe.
Now continue your access after checking the checkbox to send emails.
After the continue, you will receive your first email.
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.
I have discussed dependency injection in C# with code examples for beginners. Visit this post.
Creating an Email Service
Now that we’ve set up the Gmail API and installed the necessary packages, let’s create a service that will handle sending emails in our ASP.NET Core 5 application.
First, let’s create a new class called EmailService
in our project. This class will contain the logic for sending emails using the Gmail API.
Next, let’s define the structure of our email message class. This class should contain the following properties:
To
: The email address of the recipient.Subject
: The subject of the email.Body
: The body of the email.
We’ll also need to create a method in our EmailService
class called SendEmailAsync
that takes an instance of our email message class as a parameter. This method will handle the actual sending of the email.
To use the Gmail API to send emails, we’ll need to authenticate with the API using the credentials we created earlier. We can do this by creating a new UserCredential
object with the credentials and then using it to create a new GmailService
object.
Once we have a GmailService
object, we can use it to create a new Message
object with the details of our email message. We’ll need to encode the message body as base64 before we can send it.
Finally, we can call the GmailService.Users.Messages.Send
method to send the email. This method takes the Message
object we created earlier as a parameter and sends it using the authenticated user’s email address.
And that’s it! We’ve now created a service that can be used to send emails using the Gmail API in our ASP.NET Core 5 application.
Implementing Email Service in ASP.NET Core 5
Now that we’ve created our EmailService
, let’s integrate it into our ASP.NET Core 5 application.
First, we need to add the email service to our application’s Startup.cs
file. We can do this by registering our EmailService
class as a scoped service in the ConfigureServices
method. This will allow us to inject our email service into other classes in our application.
Next, we need to configure our application to use the Gmail API. We can do this by adding the following code to the ConfigureServices
method:
services.AddGmailEmailSender(options => {
options.ClientId = “”;
options.ClientSecret = “”;
});
This code adds a Gmail email sender to our application’s service collection and sets the client ID and client secret we created earlier as the authentication credentials.
Now that we’ve added our email service and configured the Gmail API, we can use our EmailService
to send emails in our application.
Let’s say we have a controller that needs to send an email. We can inject our EmailService
into the controller’s constructor and then call the SendEmailAsync
method to send the email. Here’s an example:
public class ExampleController : Controller
{
private readonly EmailService _emailService;
public ExampleController(EmailService emailService)
{
_emailService = emailService;
}
public async Task<IActionResult> SendEmail()
{
var email = new EmailMessage
{
To = "example@example.com",
Subject = "Hello from ASP.NET Core",
Body = "This is an email sent from an ASP.NET Core application using the Gmail API."
};
await _emailService.SendEmailAsync(email);
return Ok();
}
}
In this example, we’re creating a new EmailMessage
object and then calling the SendEmailAsync
method of our EmailService
to send the email.
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.