如何在Microsoft Bot Framework中通过ID获取Teams用户邮箱?
Hey there! I see you're working with the Microsoft Bot Framework in Node.js and need to fetch a user's email address using their ID when chatting via Microsoft Teams. Let's walk through a reliable solution for this.
1. 先检查Activity对象中的直接可用字段
In Teams, when a user sends a message, the context.activity.from object often includes their email address (if your Teams app has the necessary permissions). You can try accessing it directly first:
const userEmail = session.message.from.email;
Note that this field isn't always guaranteed to be present, so for a more reliable approach, we'll use the Microsoft Graph API.
2. 通过Microsoft Graph API获取用户邮箱
To fetch the email via the user's AAD Object ID, you'll need two key steps: configure proper permissions for your bot, then call the Graph API with an access token.
完整修改后的代码示例
const builder = require('botbuilder'); const axios = require('axios'); // For making HTTP requests to Graph API const express = require('express'); // Initialize storage and connector const inMemoryStorage = new builder.MemoryBotStorage(); const botSetting = { appId: '4c8f3u2b-c56n-4117-bc16-ec31eeb5d25c', appPassword: '4CBNO8vBGtdcGh9PoiVYottY' }; const connector = new builder.ChatConnector(botSetting); // Create bot instance const bot = new builder.UniversalBot(connector, async (session) => { try { // Get user's AAD Object ID from the incoming message const aadObjectId = session.message.from.aadObjectId; if (!aadObjectId) { session.send("Couldn't retrieve your AAD Object ID. Please check your Teams app configuration."); return; } // Step 1: Fetch access token for Graph API using bot's credentials const tokenResponse = await axios.post('https://login.microsoftonline.com/common/oauth2/v2.0/token', null, { params: { grant_type: 'client_credentials', client_id: botSetting.appId, client_secret: botSetting.appPassword, scope: 'https://graph.microsoft.com/.default' } }); const accessToken = tokenResponse.data.access_token; // Step 2: Call Graph API to get user details including email const userResponse = await axios.get(`https://graph.microsoft.com/v1.0/users/${aadObjectId}`, { headers: { Authorization: `Bearer ${accessToken}` } }); // Fallback to userPrincipalName if mail field is empty const userEmail = userResponse.data.mail || userResponse.data.userPrincipalName; // Send the email back to the user session.send(`Your email address is: ${userEmail}`); } catch (error) { console.error("Error fetching user email:", error); session.send("Sorry, I couldn't retrieve your email address right now. Please try again later."); } }).set('storage', inMemoryStorage); // Set up Express server to listen for bot messages const app = express(); app.post('/api/messages', connector.listen()); app.listen(3978, () => console.log("Bot server running on port 3978"));
关键注意事项
- Permission Configuration: In the Azure Portal, go to your Bot registration → API Permissions → Add a permission → Microsoft Graph → Application Permissions → Add
User.Read.All(orUser.ReadBasic.All), then grant admin consent for your tenant. - Install Dependencies: Don't forget to install the required packages:
npm install botbuilder axios express - Error Handling: The code includes error catching to prevent the bot from crashing if API calls fail.
- Email Fallback: If the
mailfield is null,userPrincipalNameusually works as a valid login email for the user.
内容的提问来源于stack exchange,提问作者user964409

