To use OAuth2 authentication with Gmail and Nodemailer, you will need to do the following:
- Go to the Google Developer Console and create a new project.
- Enable the Gmail API for your project.
- Go to the “Credentials” page and create a new OAuth client ID. Select “Web application” as the application type and provide a name for the client ID.
- In the “Authorized redirect URIs” field, add the URL of your app where you want the user to be redirected after they grant/deny permission.
- Click “Create” to create the client ID.
- Copy the client ID and client secret, as you will need these to configure Nodemailer.
Then, in your Node.js code, you can use the following example to send an email using Nodemailer and OAuth2 authentication:
const nodemailer = require('nodemailer');
async function main() {
// Create a new transporter using the default SMTP transport
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: 'your-email@example.com',
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
refreshToken: 'your-refresh-token',
accessToken: 'your-access-token',
expires: 1484314697598
}
});
// Define the email options
let mailOptions = {
from: '"Sender Name" <sender@example.com>',
to: 'recipient@example.com',
subject: 'Hello',
text: 'Hello, world!',
html: '<b>Hello, world!</b>'
};
// Send the email
let info = await transporter.sendMail(mailOptions);
console.log(`Message sent: ${info.messageId}`);
}
main().catch(console.error);
Note that in order to use OAuth2 authentication, you will need to obtain an access token and a refresh token from Google. You can use the google-auth-library and google-auth-oauth2 libraries to help you with this. For example:
const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client('your-client-id', 'your-client-secret', 'your-redirect-uri');
async function getAccessToken() {
const authUrl = client.generateAuthUrl({
access_type: 'offline',
scope: ['https://www.googleapis.com/auth/gmail.send']
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const code = await new Promise((resolve, reject) => {
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
resolve(code);
});
});
const { tokens } = await client.getToken(code);
console.log(tokens);
client.setCredentials(tokens);
}
getAccessToken().catch(console.error);