<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Sandeep Bajracharya's blog]]></title><description><![CDATA[Sandeep Bajracharya's blog]]></description><link>https://blogs.sandeepbajracharya.com.np</link><generator>RSS for Node</generator><lastBuildDate>Sun, 03 May 2026 16:37:07 GMT</lastBuildDate><atom:link href="https://blogs.sandeepbajracharya.com.np/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Sending email with Nodemailer and OAuth 2.0]]></title><description><![CDATA[Email sending feature is a-must in almost every application. Here is the tutorial on how we can send email using nodemailer and OAuth 2.0 🚀🔥
This first step is crucial as we need client ID and client secret which will be later added in the OAuth2 p...]]></description><link>https://blogs.sandeepbajracharya.com.np/sending-email-with-nodemailer-and-oauth-20</link><guid isPermaLink="true">https://blogs.sandeepbajracharya.com.np/sending-email-with-nodemailer-and-oauth-20</guid><category><![CDATA[Node.js]]></category><category><![CDATA[email]]></category><category><![CDATA[nodemailer]]></category><dc:creator><![CDATA[Sandeep Bajracharya]]></dc:creator><pubDate>Mon, 03 Mar 2025 18:15:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cckf4TsHAuw/upload/5e9a7c047102bd9db61b625fc65a210e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Email sending feature is a-must in almost every application. Here is the tutorial on how we can send email using nodemailer and OAuth 2.0 🚀🔥</p>
<p>This first step is crucial as we need client ID and client secret which will be later added in the OAuth2 playground to enable mail. First, we need to sign-in to <a target="_blank" href="https://console.cloud.google.com/welcome">google cloud console. If you have not cr</a>eated a project there, you need to create one and also set up a consent screen.</p>
<p>For now, I’m assuming we already have that. On the side menu, go to the “<strong>APIs and services</strong>” menu and click on “<strong>Credentials</strong>”. After that click on “<strong>CREATE CREDENTIALS</strong>” in the top-middle section. A dropdown menu will appear. From there, click on OAuth client ID. After that, select the application type you need (for now: Web application) and fill up the name you want. For “<strong>Authorised redirect URIs</strong>”, add this URI: <a target="_blank" href="https://developers.google.com/oauthplayground">https://developers.google.com/oauthplayground. This URI is of OAuth 2.0 playground. Now</a> click on “<strong>CREATE</strong>”.</p>
<p><img src="https://sandeepbajracharya.com.np/api/file-read/uploads/e50fc64c7971cd4dd64ac1f01" alt /></p>
<p><strong><em>Note: the created project might take a few minutes to hours to come into effect.</em></strong></p>
<p>Right after creating, we will get client ID and client secret. Now go to <a target="_blank" href="https://developers.google.com/oauthplayground">OAuth 2.0 playground</a>.</p>
<p><img src="https://sandeepbajracharya.com.np/api/file-read/uploads/e50fc64c7971cd4dd64ac1f02" alt /></p>
<p>On the right top, click on the setting icon. There we will see different options but one we need appears after checking on “<strong>Use your own OAuth credentials</strong>”. After checking, input fields with client ID and client secret appear. Paste those credentials we got from google console and close it. After that on the right panel in “Step 1”, search for “Gmail API v1” and click on “<a target="_blank" href="https://mail.google.com/">https://mail.google.com/</a>”. Click on the “<strong>Authorize APIs</strong>” button.</p>
<p>After success, Step 2 will be active and we can see the Authorization code and exchange button just below it. Click on the button. Now we will get “<strong>Refresh token</strong>” and “<strong>Access token</strong>”.</p>
<p>Okay now let’s do some coding 👨‍💻</p>
<ol>
<li><p>Create a project<br /> Go to your preferred terminal and run:</p>
<pre><code class="lang-bash"> npm init -y
</code></pre>
<p> This command will initialize your node project and create package.json for you.<br /> Install necessary packages:</p>
<pre><code class="lang-bash"> npm install nodemailer googleapis
</code></pre>
<p> "googleapis" package is required to authenticate and authorize.</p>
</li>
<li><p>Create env file and paste the credentials like following:</p>
<pre><code class="lang-bash"> GOOGLE_PLAYGROUND_REFRESH_TOKEN=&lt;your refresh token&gt;
 GOOGLE_APP_CLIENT_ID=&lt;your client id&gt;
 GOOGLE_APP_CLIENT_SECRET=&lt;your client secret&gt;
 GOOGLE_PLAYGROUND_REDIRECT_URI=https://developers.google.com/oauthplayground
</code></pre>
</li>
<li><p>For better read, I’ve created a config file:</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// config.js in root directory</span>

 <span class="hljs-built_in">require</span>(<span class="hljs-string">"dotenv"</span>).config();

 <span class="hljs-keyword">const</span> GOOGLE_PLAYGROUND_REFRESH_TOKEN =
   process.env.GOOGLE_PLAYGROUND_REFRESH_TOKEN;
 <span class="hljs-keyword">const</span> GOOGLE_APP_CLIENT_ID = process.env.GOOGLE_APP_CLIENT_ID;
 <span class="hljs-keyword">const</span> GOOGLE_APP_CLIENT_SECRET = process.env.GOOGLE_APP_CLIENT_SECRET;

 <span class="hljs-built_in">module</span>.exports = {
   GOOGLE_PLAYGROUND_REFRESH_TOKEN,
   GOOGLE_APP_CLIENT_ID,
   GOOGLE_APP_CLIENT_SECRET,
 };
</code></pre>
</li>
<li><p>Next, I’m creating a src/service directory and new file inside service directory<br /> From root directory, run the following commands:</p>
<pre><code class="lang-bash"> mkdir -p src/service
 touch src/service/nodemailer.js
</code></pre>
</li>
<li><p>Open the nodemailer.js file and paste the following code:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> nodemailer = <span class="hljs-built_in">require</span>(<span class="hljs-string">"nodemailer"</span>);
 <span class="hljs-keyword">const</span> { google } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"googleapis"</span>);

 <span class="hljs-keyword">const</span> {
   GOOGLE_PLAYGROUND_REDIRECT_URI,
   GOOGLE_APP_CLIENT_ID,
   GOOGLE_APP_CLIENT_SECRET,
   GOOGLE_PLAYGROUND_REFRESH_TOKEN,
 } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"../config"</span>);

 <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">initiateTransporter</span>(<span class="hljs-params">user</span>) </span>{
   <span class="hljs-keyword">try</span> {
     <span class="hljs-keyword">const</span> oAuth2client = <span class="hljs-keyword">new</span> google.auth.OAuth2(
       GOOGLE_APP_CLIENT_ID,
       GOOGLE_APP_CLIENT_SECRET,
       GOOGLE_PLAYGROUND_REDIRECT_URI
     );
     oAuth2client.setCredentials({
       <span class="hljs-attr">refresh_token</span>: GOOGLE_PLAYGROUND_REFRESH_TOKEN,
     });

     <span class="hljs-keyword">const</span> transporter = nodemailer.createTransport({
       <span class="hljs-attr">service</span>: <span class="hljs-string">"gmail"</span>,
       <span class="hljs-attr">auth</span>: {
         <span class="hljs-attr">type</span>: <span class="hljs-string">"OAuth2"</span>,
         user,
         <span class="hljs-attr">clientId</span>: GOOGLE_APP_CLIENT_ID,
         <span class="hljs-attr">clientSecret</span>: GOOGLE_APP_CLIENT_SECRET,
         <span class="hljs-attr">refreshToken</span>: GOOGLE_PLAYGROUND_REFRESH_TOKEN,
       },
     });

     <span class="hljs-keyword">return</span> transporter;
   } <span class="hljs-keyword">catch</span> (err) {
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error while initiating transporter"</span>);
     <span class="hljs-built_in">console</span>.log(err);
   }
 }

 <span class="hljs-built_in">module</span>.exports = { initiateTransporter };
</code></pre>
<p> As you can see here, this code simply authenticates and establishes a connection using googleapis. After that there is the invoke of <strong>createTransport()</strong> function provided by nodemailer.</p>
</li>
<li><p>Now create another file or function whose main purpose is to send email. Here I’ve created an email.js file at the root directory.</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> { initiateTransporter } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./service/nodemailer"</span>);

 <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">emailInitiate</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">try</span> {
     <span class="hljs-keyword">const</span> yourEmail = <span class="hljs-string">"&lt;Your email address&gt;"</span>;
     <span class="hljs-keyword">const</span> transporter = <span class="hljs-keyword">await</span> initiateTransporter(yourEmail);

     <span class="hljs-keyword">await</span> transporter.sendMail({
       <span class="hljs-attr">from</span>: yourEmail,
       <span class="hljs-attr">to</span>: <span class="hljs-string">"&lt;Email address to whom you want to send email&gt;"</span>,
       <span class="hljs-attr">subject</span>: <span class="hljs-string">"Nodemailer with OAuth"</span>,
       <span class="hljs-attr">html</span>: <span class="hljs-string">"&lt;p&gt;Hello world&lt;/p&gt;"</span>,
       <span class="hljs-attr">attachments</span>: [], <span class="hljs-comment">// include if any</span>
     });

     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Email sent"</span>);
   } <span class="hljs-keyword">catch</span> (err) {
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error while sending email"</span>);
   }
 }

 emailInitiate();
</code></pre>
</li>
<li><p>Now lets run following in your terminal:</p>
<pre><code class="lang-bash"> node src/email.js
</code></pre>
<p> Output will be displayed after email is sent successfully:</p>
<pre><code class="lang-bash"> Email sent
</code></pre>
<p> Happy coding!! 🙂</p>
</li>
</ol>
]]></content:encoded></item></channel></rss>