最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

oauth 2.0 - Got confused with access token in sending email with Nestjs, Nodemailer and OAuth2 - Stack Overflow

programmeradmin0浏览0评论

I have implemented the code below to send mail with Nodemailer and OAuth2 in a Nestjs app. It sends mails successfully. But I wonder if there is any way to refresh the access token when the token is expired. Because it just call to get the access token when the app is starting and not refresh the access token when sending mail to the users.

import { MailerModule } from "@nestjs-modules/mailer";
import { Global, Module } from "@nestjs/common";
import { HandlebarsAdapter } from "@nestjs-modules/mailer/dist/adapters/handlebars.adapter";
import { DatabaseService } from "@/base/database/database.service";
import { ConfigService } from "@nestjs/config";
import { MailService } from "@/base/mail/mail.service";
import { OAuth2Client } from "google-auth-library";

@Global()
@Module({
  imports: [
    MailerModule.forRootAsync({
      useFactory: async (
        databaseService: DatabaseService,
        configService: ConfigService,
      ) => {
        const oAuth2Client = new OAuth2Client(
          configService.get<string>("GOOGLE_CLIENT_ID"),
          configService.get<string>("GOOGLE_CLIENT_SECRET"),
        );
        oAuth2Client.setCredentials({
          refresh_token: configService.get<string>("GOOGLE_REFRESH_TOKEN"),
        });
        const response = await oAuth2Client.getAccessToken();
        const accessToken = response.token;
        console.log(accessToken);
        return {
          transport: {
            service: "gmail",
            auth: {
              type: "OAuth2",
              user: configService.get<string>("NODEMAILER_USER"),
              clientId: configService.get<string>("GOOGLE_CLIENT_ID"),
              clientSecret: configService.get<string>("GOOGLE_CLIENT_SECRET"),
              refresh_token: configService.get<string>("GOOGLE_REFRESH_TOKEN"),
              accessToken: accessToken,
            },
          },
          defaults: {
            from: `No reply <${configService.get<string>("NODEMAILER_USER")}>`,
          },
          template: {
            dir: __dirname + "/template",
            adapter: new HandlebarsAdapter(),
            options: {
              strict: true,
            },
          },
        };
      },
      inject: [DatabaseService, ConfigService],
    }),
  ],
  controllers: [],
  providers: [MailService],
  exports: [MailService],
})
export class MailModule {}

My sending mail function:

  public async sendMail(mailOptions: ISendMailOptions) {
    try {
      await this.mailerService.sendMail(mailOptions);
      this.logger.log(`Mail is sent to ${mailOptions.to}`);
    } catch (error) {
      throw error;
    }
  }

Are there any solutions for this? thanks for reading.

发布评论

评论列表(0)

  1. 暂无评论