DEV Community

Cover image for Sending Transactional emails through gmail in React NextJS GraphQL App
Nabendu
Nabendu

Posted on • Edited on • Originally published at nabendu.blog

Sending Transactional emails through gmail in React NextJS GraphQL App

I am building a demo Indian Restaurant Billing App , after completing Advanced React course by Wes Bos.

In my first article i changed the menu to hamburger menu from the normal menu.

In the second article i had given details to upload images through cloudinary.

Now, in the course Wes had taught to send “Password Reset” transactional email through a fake SMTP service Mailtrap and pointed us to use something more robust in production

Mailtrap is ok for development, where mails are not sent to recipient email. But even for a small production app, we need to send real emails to real email id.

I did my research to find a cheap and good email service to send transactional email, but all of them cost around $10 per month for the cheapest plan. Not all of us can start with that, even if our app is small. This is a good link if you want and of the services.

I did a bit more research and found that we can also send email through gmail APIs and found a great updated article on medium by Nick Roach to do so.

If your users have a gmail account(which most of us have) and you are ok with the limit of 500 mails per day, then ride along.

Follow the complete article by Nick Roach and get a Client ID, Client Secret and Refresh Token from Google Developer account.

Now, open your project which was made in after the Advanced React tutorial video 32 or open my github.

First, we make variables for Client ID, Client Secret and Refresh Token in variables.env file.

New variables.New variables.

In the file mail.js only keep the below.

mail.js reducedmail.js reduced

Now, in our Mutation.js import three new statements at the top and only take makeANiceEmail from mail.js

const { makeANiceEmail } = require('../mail');
const nodemailer = require('nodemailer');
const { google } = require("googleapis");
const OAuth2 = google.auth.OAuth2;

We do all the changes in requestReset function in Mutation.js

Here we are sending email through Oauth2 in gmail.

Sending mail by Oauth2Sending mail by Oauth2

We also have to install googleapis in our backend server, before running the code.

googleapisgoogleapis

Now, it’s time to test. Sign up with a real gmail id in your web-app.

Then, go to the Reset page(I have a different one, then the tutorial app) and give the real gmail id, which you just used to Sign-up.

Reset LinkReset Link

And here your password reset link on your real gmail account.

Password reset gmail mailPassword reset gmail mail

You can find the code till this point here.

Top comments (0)