ホームページ  >  に質問  >  本文

Nest JS の Gmail API を使用してメールを既読としてマークするにはどうすればよいですか?

私はコーディングに Nest.js を使用しており、メール データを正常に取得できるようになりました。次に、メッセージ ID で各メールを 1 つずつ取得し、メールが既読か未読かを確認したいと思います。メールが未読の場合は、既読としてマークし、データベース内で更新したいと考えています。 知っている人はコードを書き直してください。


注: データベース操作に Prisma ORM を使用しています

ああああ

P粉818306280P粉818306280283日前427

全員に返信(1)返信します

  • P粉127901279

    P粉1279012792024-01-11 12:41:24

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

    返事
    0
  • キャンセル返事