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.
本文标签:
版权声明:本文标题:oauth 2.0 - Got confused with access token in sending email with Nestjs, Nodemailer and OAuth2 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741956250a2407004.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论