如何通过REST API向Microsoft Teams发送指定用户单条通知?
Absolutely, you can implement this one-way notification scenario using production-ready Microsoft Graph API endpoints—no bots or two-way interaction required. Let’s walk through the valid options and code examples tailored to your needs:
Option 1: Send Email Notifications (Most Stable Production Choice)
If email is an acceptable channel for your notifications, the Graph API’s 1.0 /users/{user-id}/sendMail endpoint is fully supported for production use. This works with both delegated (user context) and application-only permissions.
Required Permissions
- Delegated:
Mail.Send - Application:
Mail.Send(needs admin consent)
NodeJS Example
const { Client } = require('@microsoft/microsoft-graph-client'); const { TokenCredentialAuthenticationProvider } = require('@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials'); const { ClientSecretCredential } = require('@azure/identity'); // Configure credentials (application-only flow) const credential = new ClientSecretCredential( 'your-tenant-id', 'your-client-id', 'your-client-secret' ); const authProvider = new TokenCredentialAuthenticationProvider(credential, { scopes: ['https://graph.microsoft.com/.default'] }); const client = Client.initWithMiddleware({ authProvider }); async function sendEmailNotification() { try { await client.api('/users/{target-user-id}/sendMail') .post({ message: { subject: 'Your Notification', body: { contentType: 'Text', content: 'This is a simple one-way notification from our external application.' }, toRecipients: [ { emailAddress: { address: 'target-user@domain.com' } } ] }, saveToSentItems: false }); console.log('Notification sent successfully'); } catch (error) { console.error('Error sending email:', error); } } sendEmailNotification();
Python Example
from msgraph.core import GraphClient from azure.identity import ClientSecretCredential # Configure credentials credential = ClientSecretCredential( tenant_id='your-tenant-id', client_id='your-client-id', client_secret='your-client-secret' ) client = GraphClient(credential=credential, scopes=['https://graph.microsoft.com/.default']) def send_email_notification(): try: payload = { "message": { "subject": "Your Notification", "body": { "contentType": "Text", "content": "This is a simple one-way notification from our external application." }, "toRecipients": [ { "emailAddress": { "address": "target-user@domain.com" } } ] }, "saveToSentItems": False } response = client.post(f'/users/{{target-user-id}}/sendMail', json=payload) response.raise_for_status() print("Notification sent successfully") except Exception as e: print(f"Error sending email: {e}") send_email_notification()
Java Example
import com.azure.identity.ClientSecretCredential; import com.azure.identity.ClientSecretCredentialBuilder; import com.microsoft.graph.models.*; import com.microsoft.graph.requests.GraphServiceClient; import okhttp3.Request; import java.util.Arrays; public class EmailNotificationSender { public static void main(String[] args) { // Configure credentials ClientSecretCredential credential = new ClientSecretCredentialBuilder() .tenantId("your-tenant-id") .clientId("your-client-id") .clientSecret("your-client-secret") .build(); GraphServiceClient<Request> client = GraphServiceClient.builder() .authenticationProvider(request -> { String token = credential.getToken("https://graph.microsoft.com/.default").block().getToken(); request.addHeader("Authorization", "Bearer " + token); return request; }) .buildClient(); try { Message message = new Message(); message.subject = "Your Notification"; ItemBody body = new ItemBody(); body.contentType = BodyType.TEXT; body.content = "This is a simple one-way notification from our external application."; message.body = body; Recipient recipient = new Recipient(); EmailAddress emailAddress = new EmailAddress(); emailAddress.address = "target-user@domain.com"; recipient.emailAddress = emailAddress; message.toRecipients = Arrays.asList(recipient); client.users("{target-user-id}") .sendMail(UserSendMailParameterSet.newBuilder() .withMessage(message) .withSaveToSentItems(false) .build()) .buildRequest() .post(); System.out.println("Notification sent successfully"); } catch (Exception e) { System.err.println("Error sending email: " + e.getMessage()); } } }
Option 2: Send Teams Chat Messages (Production-Ready)
If you need to send notifications directly to a user’s Teams chat, you can use the 1.0 Graph API endpoints to create a one-on-one chat (if it doesn’t exist) and send a message to it. This avoids beta endpoints and works with application-only permissions.
Required Permissions
- Application:
Chat.CreateandChatMessage.Send(admin consent required)
Key Notes
- First, check if a chat already exists between your app’s identity and the target user (using
GET /chats?$filter=members/any(m:m/emailAddress/address eq 'target-user@domain.com')). If not, create one withPOST /chats. - Then send a message to the chat using
POST /chats/{chat-id}/messages.
NodeJS Example (Simplified)
// Reuse the client setup from the email example above async function sendTeamsChatNotification() { try { // Step 1: Create or get the chat const chat = await client.api('/chats') .post({ chatType: 'oneOnOne', members: [ { '@odata.type': '#microsoft.graph.aadUserConversationMember', roles: ['owner'], user: { id: '{target-user-id}' } } ] }); // Step 2: Send message to the chat await client.api(`/chats/${chat.id}/messages`) .post({ body: { contentType: 'text', content: 'This is a one-way Teams notification from our external application.' } }); console.log('Teams notification sent successfully'); } catch (error) { console.error('Error sending Teams chat message:', error); } } sendTeamsChatNotification();
Why Your Previous Attempts Failed
- The Beta
Chat/ChatMessageendpoints are not intended for production, so avoiding them is the right call. - The 1.0 preview
sendmethod you encountered was likely deprecated or required specific permissions/scopes you didn’t have. The endpoints above are fully supported in production.
Additional Reference Tips
- Focus on the 1.0 version of the Microsoft Graph API docs for
sendMailandChat/ChatMessageoperations—these are production-ready. - Verify your app has the correct permissions (with admin consent if using application-only flow) in the Azure Portal.
内容的提问来源于stack exchange,提问作者user3667143

