如何在Nest.js中使用Gmail API将电子邮件标记为已读?

huangapple go评论102阅读模式
英文:

how to mark the email as read using gmail api in nest js?

问题

我正在使用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 emailId = response.data.id;
      const fetchingEmailById = `https://gmail.googleapis.com/gmail/v1/users/eamil@gmail.com/messages/${emailId}`;
      const emailResponse = await axios.get(fetchingEmailById, config);

      const emailData = emailResponse.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);
    }
  }
}

请注意,你需要在注释中提到的部分添加适当的代码来处理邮件数据和将其标记为已读。

英文:

I am using Nest.js for the code, and now I am successfully fetching email data. Now, I want to individually get each email by message ID and check if the email is read or unread. If the email is unread, I want to mark it as read and update it in the database.
Anyone who know please rewrite the code for it,


Note: for Db i am using 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() ,
});
// fetchAll 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);
// fetchign email by 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);
}
}
}

答案1

得分: 1

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(),
      });

      // Fetch all email IDs
      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);
      const emailIds = response.data.messages.map((message: any) => message.id);

      for (const emailId of emailIds) {
        // Fetch individual email by ID
        const fetchingEmailById = `https://gmail.googleapis.com/gmail/v1/users/email@gmail.com/messages/${emailId}`;
        const emailResponse = await axios.get(fetchingEmailById, config);

        const emailData = emailResponse.data;
        console.log(emailData);

        // Check if the email is unread and mark it as read
        if (!emailData.labelIds.includes('UNREAD')) {
          continue; // Skip if the email is already read
        }

        // Mark the email as read
        await markEmailAsRead(emailId, config);

        // Update the email status in the database here
        // Replace the following line with your database update logic
        console.log(`Marked email with ID ${emailId} as read.`);
      }
    } catch (err) {
      console.error('Error fetching emails:', err.message);
    }
  }

  // Helper function to mark an email as read
  async markEmailAsRead(emailId: string, config: any) {
    const markAsReadUrl = `https://gmail.googleapis.com/gmail/v1/users/email@gmail.com/messages/${emailId}/modify`;
    const requestBody = {
      removeLabelIds: ['UNREAD'],
    };
    await axios.post(markAsReadUrl, requestBody, config);
  }
}
英文:
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(),
});
// Fetch all email IDs
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);
const emailIds = response.data.messages.map((message: any) => message.id);
for (const emailId of emailIds) {
// Fetch individual email by ID
const fetchingEmailById = `https://gmail.googleapis.com/gmail/v1/users/email@gmail.com/messages/${emailId}`;
const emailResponse = await axios.get(fetchingEmailById, config);
const emailData = emailResponse.data;
console.log(emailData);
// Check if the email is unread and mark it as read
if (!emailData.labelIds.includes('UNREAD')) {
continue; // Skip if the email is already read
}
// Mark the email as read
await markEmailAsRead(emailId, config);
// Update the email status in the database here
// Replace the following line with your database update logic
console.log(`Marked email with ID ${emailId} as read.`);
}
} catch (err) {
console.error('Error fetching emails:', err.message);
}
}
// Helper function to mark an email as read
async markEmailAsRead(emailId: string, config: any) {
const markAsReadUrl = `https://gmail.googleapis.com/gmail/v1/users/email@gmail.com/messages/${emailId}/modify`;
const requestBody = {
removeLabelIds: ['UNREAD'],
};
await axios.post(markAsReadUrl, requestBody, config);
}
}

huangapple
  • 本文由 发表于 2023年7月27日 18:36:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778896.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定