How to send smtp.sendgrid.net mails with Microsoft Oautheentication in Node Js?

KRANTHI KUMAR REDDY 1 Reputation point
2022-12-18T07:06:00.15+00:00

I am using smtp.sendgrid.net host for sending emails in Node js. I am trying to Implement sending sendgrid emails with Microsoft O Authentication in Node Js. please help me on this issue.

Microsoft Security Microsoft Authenticator
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. Ali AlEnezi 1,081 Reputation points
    2022-12-20T19:20:20.937+00:00

    Dear @KRANTHI KUMAR REDDY ,

    To send emails using SendGrid and Microsoft OAuth in Node.js, you will need to install the SendGrid Node.js library and the passport-azure-ad library. You can install these libraries using the following command:

    npm install @sendgrid/mail passport-azure-ad

    Then, you will need to require the libraries in your code and set up your SendGrid API key and Azure AD OAuth configuration. Here is an example of how you can set up the SendGrid API key and Azure AD OAuth configuration:

    const sendgrid = require('@sendgrid/mail');
    const passport = require('passport');
    const OAuth2Strategy = require('passport-azure-ad').OIDCStrategy;

    // Set up SendGrid API key
    sendgrid.setApiKey(process.env.SENDGRID_API_KEY);

    // Set up Azure AD OAuth configuration
    passport.use(new OAuth2Strategy({
    clientID: process.env.AZURE_CLIENT_ID,
    clientSecret: process.env.AZURE_CLIENT_SECRET,
    callbackURL: process.env.AZURE_CALLBACK_URL,
    resource: 'https://graph.microsoft.com',
    tenant: process.env.AZURE_TENANT_ID,
    responseType: 'code',
    responseMode: 'query'
    },
    function (accessToken, refreshToken, params, profile, done) {
    return done(null, { accessToken, refreshToken, params, profile });
    }
    ));

    Once you have set up the API key and OAuth configuration, you can use the SendGrid API to send emails using the following code:

    // Set up email parameters
    const msg = {
    to: 'recipient@ssss .com',
    from: 'sender@ssss .com',
    subject: 'Test email using SendGrid and Microsoft OAuth',
    text: 'This is a test email sent using SendGrid and Microsoft OAuth.'
    };

    // Send the email
    sendgrid.send(msg);

    Good luck!


  2. KRANTHI KUMAR REDDY 1 Reputation point
    2022-12-21T05:10:33.553+00:00

    can you please share sample code for it in Node JS.

    0 comments No comments

  3. KRANTHI KUMAR REDDY 1 Reputation point
    2022-12-21T06:08:13.747+00:00

    Hi I am using below mentioned code in Node JS. as per your suggestion but how Sendgrid verify my Token with Microsoft Azure.

    const express = require('express');
    const app = express();
    const Server = require('http').Server;
    const server = new Server(app);

    const msal = require('@azure/msal-node');

    const clientSecret = 'ClientSecreat';
    const clientId = 'clientID';
    const tenantId = 'tenantID';
    const aadEndpoint = 'https://login.microsoftonline.com';
    const graphEndpoint = 'https://graph.microsoft.com';
    const sendgrid = require('@sendgrid/mail');
    const {Client} = require('@sendgrid/client');

    app.get('/sendgridSmtp', (req, res) => {
    // Set up SendGrid API key
    Client.setApiKey(process.env.APIKEY);

    const msalConfig = {  
        auth: {  
            clientId: clientId,  
            authority: aadEndpoint + '/' + tenantId,  
            clientSecret: clientSecret  
        },  
    };  
    
    const tokenRequest = {  
        scopes: [graphEndpoint + '/.default'],  
    };  
    
    const cca = new msal.ConfidentialClientApplication(msalConfig);  
    let tokenInfo = "";  
    
    async function getTokenInfo() {  
        tokenInfo = await cca.acquireTokenByClientCredential(tokenRequest);  
        var accessToken = tokenInfo.accessToken;  
    
        async function sendsengridMail() {  
            const msg = {  
                to: '******@to.com',  
                from: '******@from.com',  
                subject: 'Test email using SendGrid and Microsoft OAuth',  
                text: 'This is a test email sent using SendGrid and Microsoft OAuth.'  
            };  
    
            // Send the email  
            const headers = new fetch.Headers();  
            const bearer = `Bearer ${tokenInfo.accessToken}`;  
    
            headers.append('Authorization', bearer);  
            //headers.append('Content-Type', 'application/json');  
    
            const request = {  
                method: 'POST',  
                url: 'https://api.sendgrid.com/v3/mail/send',  
                headers: headers,  
                body: msg,  
            };  
    
    
            Client.request(request)  
                .then(([response, body]) => {  
                    console.log(response.statusCode);  
                    console.log(response.body);  
                })  
        }  
    
        sendsengridMail();  
    }  
    getTokenInfo();  
    

    });

    0 comments No comments

  4. KRANTHI KUMAR REDDY 1 Reputation point
    2022-12-22T05:51:18.537+00:00

    please help on this issue. How sendGrid verify my token with Microsoft Azure.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.