Bagaimana untuk menandai e-mel sebagai dibaca menggunakan API Gmail dalam Nest JS?
P粉818306280
P粉818306280 2024-01-10 18:00:25
0
1
489

Saya menggunakan Nest.js untuk pengekodan dan kini saya berjaya mendapatkan data e-mel. Sekarang saya ingin mendapatkan setiap e-mel satu demi satu dengan id mesej dan menyemak sama ada e-mel itu dibaca atau belum dibaca. Jika e-mel itu belum dibaca, saya ingin menandainya sebagai dibaca dan mengemas kininya dalam pangkalan data. Sesiapa yang tahu sila tulis semula kod untuk ini,


Nota: Saya menggunakan Prisma ORM untuk operasi pangkalan data

// 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

membalas semua(1)
P粉127901279
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);
  }
}
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan