admin管理员组

文章数量:1313787

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.

本文标签: