OAuth2 Authentication

For more secure authentication, especially with Gmail, you can use OAuth2. This avoids hardcoding credentials and enhances security.

Setting Up OAuth2:

  1. Create OAuth2 Credentials: Go to the Google Developer Console and create OAuth2 credentials.
  2. Install Required Libraries:
npm install googleapis nodemailer
  1. Configure Nodemailer with OAuth2:
const nodemailer = require('nodemailer'); const { google } = require('googleapis'); const oAuth2Client = new google.auth.OAuth2( process.env.CLIENT_ID, process.env.CLIENT_SECRET, 'https://developers.google.com/oauthplayground' ); oAuth2Client.setCredentials({ refresh_token: process.env.REFRESH_TOKEN }); const sendMail = async () => { try { const accessToken = await oAuth2Client.getAccessToken(); const transporter = nodemailer.createTransport({ service: 'gmail', auth: { type: 'OAuth2', user: process.env.EMAIL_USER, clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, refreshToken: process.env.REFRESH_TOKEN, accessToken: accessToken.token } }); const mailOptions = { from: 'Your Name <[email protected]>', to: '[email protected]', subject: 'Hello OAuth2', text: 'This is an email sent using OAuth2 authentication.' }; const result = await transporter.sendMail(mailOptions); console.log('Email sent:', result); } catch (error) { console.error('Error sending email:', error); } }; sendMail();

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *