Sushant Kumar
Sushant Kumar

Reputation: 253

Sending mail using gmail api from nodejs server

What I want to do is to send user a mail, a user's password , from my node js rest api. I want to know how to send email using gmail api and api keys only.

Upvotes: 0

Views: 3060

Answers (2)

sendra
sendra

Reputation: 688

If what you want is to send an email using Gmail API without the need for authentications you must use a service acount and use jwt to authenticate.

example code:

const google = require('googleapis');
const gmail = google.gmail('v1');

const key = require('./mailing-bd0ff2b11546.json')//service acount jwt auth

    let jwtClient = new google.auth.JWT(
        key.client_email,
        null,
        key.private_key,
        ['https://mail.google.com/'],
        '<mail to suplant>'
    );
    function getMessagesList(data) {
        return new Promise((resolve, reject) => {


            jwtClient.authorize(function (err, tokens) {
                if (err) {
                    console.error(err);
                } else {
                    gmail.users.messages.list({
                        auth: jwtClient,
                        userId: 'me',
                        labelIds: 'INBOX'
                    }, (err, messageList) => {

                   ...
                   ...
                   ...

Here are some links to documentation: Creating a service account

stackoverflow example

Upvotes: 0

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117321

Google discontinued client login (login and password) on all of its APIs in 2015. You cant access a Google API with login and password. Your users will need to authenticate using Oauth2.

API key is used for accessing public data only. Gmail is private user data and requires you to have access in order to access the data.

If you must use the login and password then I suggest you try and go though the SMTP or IMAP servers. I am not a node dev sorry I can not help you with that.

Upvotes: 2

Related Questions