Microsoft Graph を使用して TypeScript アプリに電子メール機能を追加する

この記事では、Microsoft Graph メール API を使用して 、Build TypeScript アプリで 作成したアプリケーションを Microsoft Graph で拡張します。 Microsoft Graph を使用して、ユーザーの受信トレイを一覧表示し、メールを送信します。

ユーザーの受信トレイを一覧表示する

まず、ユーザーのメール 受信トレイにメッセージを一覧表示します。

  1. graphHelper.ts開き、次の関数を追加します。

    export async function getInboxAsync(): Promise<PageCollection> {
      // Ensure client isn't undefined
      if (!_userClient) {
        throw new Error('Graph has not been initialized for user auth');
      }
    
      return _userClient
        .api('/me/mailFolders/inbox/messages')
        .select(['from', 'isRead', 'receivedDateTime', 'subject'])
        .top(25)
        .orderby('receivedDateTime DESC')
        .get();
    }
    
  2. index.tsの空の ListInboxAsync 関数 次のように置き換えます。

    async function listInboxAsync() {
      try {
        const messagePage = await graphHelper.getInboxAsync();
        const messages: Message[] = messagePage.value;
    
        // Output each message's details
        for (const message of messages) {
          console.log(`Message: ${message.subject ?? 'NO SUBJECT'}`);
          console.log(`  From: ${message.from?.emailAddress?.name ?? 'UNKNOWN'}`);
          console.log(`  Status: ${message.isRead ? 'Read' : 'Unread'}`);
          console.log(`  Received: ${message.receivedDateTime}`);
        }
    
        // If @odata.nextLink is not undefined, there are more messages
        // available on the server
        const moreAvailable = messagePage['@odata.nextLink'] != undefined;
        console.log(`\nMore messages available? ${moreAvailable}`);
      } catch (err) {
        console.log(`Error getting user's inbox: ${err}`);
      }
    }
    
  3. アプリを実行し、サインインし、オプション 2 を選択して受信トレイを一覧表示します。

    [1] Display access token
    [2] List my inbox
    [3] Send mail
    [4] Make a Graph call
    [0] Exit
    
    Select an option [1...4 / 0]: 2
    Message: Updates from Ask HR and other communities
      From: Contoso Demo on Yammer
      Status: Read
      Received: 12/30/2021 4:54:54 AM -05:00
    Message: Employee Initiative Thoughts
      From: Patti Fernandez
      Status: Read
      Received: 12/28/2021 5:01:10 PM -05:00
    Message: Voice Mail (11 seconds)
      From: Alex Wilber
      Status: Unread
      Received: 12/28/2021 5:00:46 PM -05:00
    Message: Our Spring Blog Update
      From: Alex Wilber
      Status: Unread
      Received: 12/28/2021 4:49:46 PM -05:00
    Message: Atlanta Flight Reservation
      From: Alex Wilber
      Status: Unread
      Received: 12/28/2021 4:35:42 PM -05:00
    Message: Atlanta Trip Itinerary - down time
      From: Alex Wilber
      Status: Unread
      Received: 12/28/2021 4:22:04 PM -05:00
    
    ...
    
    More messages available? true
    

getInboxAsync の説明

getInboxAsync関数のコードについて考えてみましょう。

既知のメール フォルダーへのアクセス

関数は /me/mailFolders/inbox/messages_userClient.api 要求ビルダーに渡します。これにより、 List messages API への要求がビルドされます。 API エンドポイントの /mailFolders/inbox 部分が含まれているため、API は要求されたメール フォルダー内のメッセージのみを返します。 この場合、受信トレイはユーザーのメールボックス内の既定の既知のフォルダーであるため、既知の名前を使用してアクセスできます。 既定以外のフォルダーには、既知の名前をメール フォルダーの ID プロパティに置き換えることで、同じ方法でアクセスされます。 使用可能な既知のフォルダー名の詳細については、「 mailFolder リソースの種類」を参照してください。

コレクションへのアクセス

1 つのオブジェクトを返す前のセクションの getUserAsync 関数とは異なり、このメソッドはメッセージのコレクションを返します。 コレクションを返す Microsoft Graph のほとんどの API では、使用可能なすべての結果が 1 つの応答で返されるわけではありません。 代わりに、 ページングを 使用して結果の一部を返しながら、クライアントが次のページを要求するメソッドを提供します。

既定のページ サイズ

ページングを使用する API では、既定のページ サイズが実装されます。 メッセージの場合、既定値は 10 です。 クライアントは、 $top クエリ パラメーターを使用して、より多く (またはそれ以下) を要求できます。 getInboxAsyncでは、.top(25) メソッドを使用して$topを追加します。

注:

.top()に渡される値は、明示的な数値ではなく、上限です。 API は、指定した値までのメッセージ数 返します。

後続のページを取得する

サーバーで使用可能な結果が増える場合、コレクション応答には、次のページにアクセスするための API URL を含む @odata.nextLink プロパティが含まれます。 JavaScript クライアント ライブラリは、 PageCollection オブジェクトに対してこのプロパティを公開します。 このプロパティが未定義でない場合は、使用可能な結果が増えます。

@odata.nextLinkの値を_userClient.apiに渡して、結果の次のページを取得できます。 または、クライアント ライブラリの PageIterator オブジェクトを使用して、 使用可能なすべてのページを反復処理することもできます。

コレクションを並べ替える

関数は、要求に対して orderby メソッドを使用して、メッセージの受信時刻 (receivedDateTime プロパティ) で並べ替えられた結果を要求します。 最近受信したメッセージが最初に一覧表示されるように、DESC キーワード (keyword)が含まれます。 このメソッドは、 $orderby クエリ パラメーター を API 呼び出しに追加します。

メールを送信する

次に、認証されたユーザーとして電子メール メッセージを送信する機能を追加します。

  1. graphHelper.ts開き、次の関数を追加します。

    export async function sendMailAsync(
      subject: string,
      body: string,
      recipient: string,
    ) {
      // Ensure client isn't undefined
      if (!_userClient) {
        throw new Error('Graph has not been initialized for user auth');
      }
    
      // Create a new message
      const message: Message = {
        subject: subject,
        body: {
          content: body,
          contentType: 'text',
        },
        toRecipients: [
          {
            emailAddress: {
              address: recipient,
            },
          },
        ],
      };
    
      // Send the message
      return _userClient.api('me/sendMail').post({ message: message });
    }
    
  2. index.tsの空の sendMailAsync 関数 次のように置き換えます。

    async function sendMailAsync() {
      try {
        // Send mail to the signed-in user
        // Get the user for their email address
        const user = await graphHelper.getUserAsync();
        const userEmail = user?.mail ?? user?.userPrincipalName;
    
        if (!userEmail) {
          console.log("Couldn't get your email address, canceling...");
          return;
        }
    
        await graphHelper.sendMailAsync(
          'Testing Microsoft Graph',
          'Hello world!',
          userEmail,
        );
        console.log('Mail sent.');
      } catch (err) {
        console.log(`Error sending mail: ${err}`);
      }
    }
    
  3. アプリを実行し、サインインし、オプション 3 を選択して自分にメールを送信します。

    [1] Display access token
    [2] List my inbox
    [3] Send mail
    [4] Make a Graph call
    [0] Exit
    
    Select an option [1...4 / 0]: 3
    Mail sent.
    

    注:

    Microsoft 365 開発者プログラムの開発者テナントでテストしている場合は、送信したメールが配信されず、配信不能レポートが届く場合があります。 テナントからのメール送信のブロックを解除する場合は、Microsoft 365 管理センターからサポートにお問い合わせください。

  4. メッセージが受信されたことを確認するには、オプション 2 を選択して受信トレイを一覧表示します。

sendMailAsync の説明

sendMailAsync関数のコードについて考えてみましょう。

メールの送信

関数は /me/sendMail_userClient.api 要求ビルダーに渡します。これにより、 メール 送信 API への要求がビルドされます。 要求ビルダーは、送信するメッセージを表す Message オブジェクトを受け取ります。

オブジェクトの作成

データのみを読み取る Microsoft Graph の以前の呼び出しとは異なり、この呼び出しではデータが作成されます。 クライアント ライブラリを使用して項目を作成するには、データを表す クラスのインスタンス (この場合は Message) を作成し、目的のプロパティを設定してから、API 呼び出しで送信します。 呼び出しはデータを送信しているため、getの代わりに post メソッドが使用されます。

次の手順