如何在Nest JS中使用Gmail API将电子邮件标记为已读?
P粉818306280
P粉818306280 2024-01-10 18:00:25
0
1
496

我正在使用Nest.js进行编码,现在我成功地获取了电子邮件数据。现在,我想通过消息ID逐个获取每封电子邮件,并检查该电子邮件是否已读或未读。如果电子邮件未读,我想将其标记为已读并在数据库中进行更新。 任何了解的人请为此重写代码,


注意:我正在使用Prisma ORM进行数据库操作

// google-sheet.service.ts
    import { Injectable } from '@nestjs/common';
    import { google } from 'googleapis';
    import { JWT } from 'google-auth-library';
    import { EnvironmentService } from 'src/core/environments/environments.service';
    import axios from 'axios';
    @Injectable()
    export class GmailService {
      constructor(private environmentService: EnvironmentService) {}
    
      async getEMails() {
        try {
          const oAuth2Client = new google.auth.OAuth2(
            this.environmentService.clientId(),
            this.environmentService.clientSecret(),
            this.environmentService.googleUri(),
          );
    
          await oAuth2Client.setCredentials({
            refresh_token:this.environmentService.refresh_token() ,
          });
    
          // 获取所有id
          const fetchingIdUrl = `https://gmail.googleapis.com/gmail/v1/users/email@gmail.com/messages/`;
    
          const { token } = await oAuth2Client.getAccessToken();
          const config: any = {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          };
    
          const response = await axios.get(fetchingIdUrl, config);
          // 通过id获取邮件
          const fetchingEmailById = `https://gmail.googleapis.com/gmail/v1/users/eamil@gmail.com/messages/${response.data.id}`;
          const emailResponse = await axios.get(fetchingEmailById, config);
    
          const emailData = response.data;
          console.log(emailData);
    
          // emailData.payload.parts.forEach((part, index) => {
          //   if (part.body.size > 0) {
          //     const bodyContent = Buffer.from(part.body.data, 'base64').toString();
          //     console.log('Body Content:');
          //     console.log(bodyContent);
          //   }
          // });
        } catch (err) {
          console.error('Error fetching emails:', err.message);
        }
      }
    }

P粉818306280
P粉818306280

全部回复(1)
P粉127901279

雷雷

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板