この記事では、「Microsoft Graph メール API を使用して Microsoft Graph を使用して Java アプリをビルド する」で作成したアプリケーションを拡張します。 Microsoft Graph を使用して、ユーザーの受信トレイを一覧表示し、メールを送信します。
ユーザーの受信トレイを一覧表示する
まず、ユーザーのメール 受信トレイにメッセージを一覧表示します。
Graph.javaを開き、次の関数を
Graphクラスに追加します。public static MessageCollectionResponse getInbox() throws Exception { // Ensure client isn't null if (_userClient == null) { throw new Exception("Graph has not been initialized for user auth"); } return _userClient.me() .mailFolders() .byMailFolderId("inbox") .messages() .get(requestConfig -> { requestConfig.queryParameters.select = new String[] { "from", "isRead", "receivedDateTime", "subject" }; requestConfig.queryParameters.top = 25; requestConfig.queryParameters.orderby = new String[] { "receivedDateTime DESC" }; }); }App.javaの空の
listInbox関数 を 次のように置き換えます。private static void listInbox() { try { final MessageCollectionResponse messages = Graph.getInbox(); // Output each message's details for (Message message: messages.getValue()) { System.out.println("Message: " + message.getSubject()); System.out.println(" From: " + message.getFrom().getEmailAddress().getName()); System.out.println(" Status: " + (message.getIsRead() ? "Read" : "Unread")); System.out.println(" Received: " + message.getReceivedDateTime() // Values are returned in UTC, convert to local time zone .atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime() .format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT))); } final Boolean moreMessagesAvailable = messages.getOdataNextLink() != null; System.out.println("\nMore messages available? " + moreMessagesAvailable); } catch (Exception e) { System.out.println("Error getting inbox"); System.out.println(e.getMessage()); } }アプリを実行し、サインインし、オプション 2 を選択して受信トレイを一覧表示します。
Please choose one of the following options: 0. Exit 1. Display access token 2. List my inbox 3. Send mail 4. Make a Graph call 2 Message: Updates from Ask HR and other communities From: Contoso Demo on Yammer Status: Read Received: 12/30/2021, 4:54:54 AM Message: Employee Initiative Thoughts From: Patti Fernandez Status: Read Received: 12/28/2021, 5:01:10 PM Message: Voice Mail (11 seconds) From: Alex Wilber Status: Unread Received: 12/28/2021, 5:00:46 PM Message: Our Spring Blog Update From: Alex Wilber Status: Unread Received: 12/28/2021, 4:49:46 PM Message: Atlanta Flight Reservation From: Alex Wilber Status: Unread Received: 12/28/2021, 4:35:42 PM Message: Atlanta Trip Itinerary - down time From: Alex Wilber Status: Unread Received: 12/28/2021, 4:22:04 PM ... More messages available? true
getInbox の説明
getInbox関数のコードについて考えてみましょう。
既知のメール フォルダーへのアクセス
関数は、list messages API への要求をビルドする_userClient.me().mailFolders().byMailFolderId("inbox").messages()要求ビルダーを使用します。
byMailFolderId("inbox")要求ビルダーが含まれているため、API は要求されたメール フォルダー内のメッセージのみを返します。 この場合、受信トレイはユーザーのメールボックス内の既定の既知のフォルダーであるため、既知の名前を使用してアクセスできます。 既定以外のフォルダーには、既知の名前をメール フォルダーの ID プロパティに置き換えることで、同じ方法でアクセスされます。 使用可能な既知のフォルダー名の詳細については、「 mailFolder リソースの種類」を参照してください。
コレクションへのアクセス
1 つのオブジェクトを返す前のセクションの getUser 関数とは異なり、このメソッドはメッセージのコレクションを返します。 コレクションを返す Microsoft Graph のほとんどの API では、使用可能なすべての結果が 1 つの応答で返されるわけではありません。 代わりに、 ページングを 使用して結果の一部を返しながら、クライアントが次のページを要求するメソッドを提供します。
既定のページ サイズ
ページングを使用する API では、既定のページ サイズが実装されます。 メッセージの場合、既定値は 10 です。 クライアントは、 $top クエリ パラメーターを使用して、より多く (またはそれ以下) を要求できます。
getInboxでは、$topの追加は、要求構成の top プロパティを使用して実行されます。
注:
topで設定される値は、明示的な数値ではなく、上限です。 API は、指定した値までのメッセージ数 を 返します。
後続のページを取得する
サーバーで使用可能な結果が増える場合、コレクション応答には、次のページにアクセスするための API URL を含む @odata.nextLink プロパティが含まれます。 Java クライアント ライブラリは、コレクション応答オブジェクトに getOdataNextLink メソッドを提供します。 このメソッドが null 以外を返す場合は、使用可能な結果が増えます。
コレクションを並べ替える
関数は、要求構成で orderBy プロパティを使用して、メッセージの受信時刻 (receivedDateTime プロパティ) で並べ替えられた結果を要求します。 最近受信したメッセージが最初に一覧表示されるように、DESC キーワード (keyword)が含まれます。 このプロパティは、 $orderby クエリ パラメーター を API 呼び出しに追加します。
メールを送信する
次に、認証されたユーザーとして電子メール メッセージを送信する機能を追加します。
Graph.javaを開き、次の関数を
Graphクラスに追加します。public static void sendMail(String subject, String body, String recipient) throws Exception { // Ensure client isn't null if (_userClient == null) { throw new Exception("Graph has not been initialized for user auth"); } // Create a new message final Message message = new Message(); message.setSubject(subject); final ItemBody itemBody = new ItemBody(); itemBody.setContent(body); itemBody.setContentType(BodyType.Text); message.setBody(itemBody); final EmailAddress emailAddress = new EmailAddress(); emailAddress.setAddress(recipient); final Recipient toRecipient = new Recipient(); toRecipient.setEmailAddress(emailAddress); message.setToRecipients(List.of(toRecipient)); final SendMailPostRequestBody postRequest = new SendMailPostRequestBody(); postRequest.setMessage(message); // Send the message _userClient.me() .sendMail() .post(postRequest); }App.javaの空の
sendMail関数 を 次のように置き換えます。private static void sendMail() { try { // Send mail to the signed-in user // Get the user for their email address final User user = Graph.getUser(); final String email = user.getMail() == null ? user.getUserPrincipalName() : user.getMail(); Graph.sendMail("Testing Microsoft Graph", "Hello world!", email); System.out.println("\nMail sent."); } catch (Exception e) { System.out.println("Error sending mail"); System.out.println(e.getMessage()); } }アプリを実行し、サインインし、オプション 3 を選択して自分にメールを送信します。
Please choose one of the following options: 0. Exit 1. Display access token 2. List my inbox 3. Send mail 4. Make a Graph call 3 Mail sent.注:
Microsoft 365 開発者プログラムの開発者テナントでテストしている場合は、送信したメールが配信されず、配信不能レポートが届く場合があります。 テナントからのメール送信のブロックを解除する場合は、Microsoft 365 管理センターからサポートにお問い合わせください。
メッセージが受信されたことを確認するには、オプション 2 を選択して受信トレイを一覧表示します。
sendMail の説明
sendMail関数のコードについて考えてみましょう。
メールの送信
関数は、メール送信 API への要求をビルドする_userClient.me().sendMail()要求ビルダーを使用します。 要求ビルダーは、送信するメッセージを含む SendMailPostRequestBody オブジェクトを受け取ります。
オブジェクトの作成
データのみを読み取る Microsoft Graph の以前の呼び出しとは異なり、この呼び出しではデータが作成されます。 クライアント ライブラリを使用して項目を作成するには、new キーワード (keyword)を使用してデータ (この場合はcom.microsoft.graph.models.Message) を表す クラスのインスタンスを作成し、目的のプロパティを設定してから、API 呼び出しで送信します。 呼び出しはデータを送信しているため、getの代わりに post メソッドが使用されます。