You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于使用Outlook API在PHP/JavaScript应用中发送邮件的技术咨询

Help with Outlook API for Sending Emails in PHP/JavaScript

Ugh, I get it—those MSDN docs can feel like reading a foreign language when you’re just trying to send a simple email from your PHP/JS app. Let’s break this down so you can get up and running quickly.

First: What Language Are Those Docs Using?

The code examples in the linked MSDN doc are mostly in C# (using the Office 365 SDK for .NET), but they also include raw HTTP request/response snippets which are universal. You can adapt those raw requests to any language—including PHP and JS. Quick note: The doc you linked uses the older Outlook REST API, but Microsoft recommends using the Microsoft Graph API (which is what the examples below use) since it’s more robust and actively maintained.

PHP Example: Send Email via cURL

Here's a working PHP script that uses cURL to send an email through the Graph API. You’ll need a valid OAuth2 access token first (you can get this via the Microsoft Identity Platform flow):

<?php
// Replace with your actual access token
$accessToken = 'YOUR_ACCESS_TOKEN_HERE';

// Graph API endpoint for sending emails
$endpoint = 'https://graph.microsoft.com/v1.0/me/sendMail';

// Email payload
$emailData = [
    'message' => [
        'subject' => 'Test Email from PHP',
        'body' => [
            'contentType' => 'Text',
            'content' => 'Hello from my PHP app!'
        ],
        'toRecipients' => [
            [
                'emailAddress' => [
                    'address' => 'recipient@example.com'
                ]
            ]
        ]
    ],
    'saveToSentItems' => true
];

// Initialize cURL request
$ch = curl_init($endpoint);

// Set cURL options
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $accessToken,
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($emailData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute request and handle response
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

if ($httpCode === 202) {
    echo "Email sent successfully!";
} else {
    echo "Error sending email: " . $response;
}
?>

JavaScript Example (Browser/Node.js)

For JavaScript, you can use the native fetch API (browser) or axios (Node.js). Here’s a browser-side example (note: you’ll need to handle OAuth2 authentication properly to avoid CORS issues):

// Replace with your actual access token
const accessToken = 'YOUR_ACCESS_TOKEN_HERE';

// Email data
const emailData = {
    message: {
        subject: 'Test Email from JavaScript',
        body: {
            contentType: 'HTML',
            content: '<p>Hello from my JS app!</p>'
        },
        toRecipients: [
            {
                emailAddress: {
                    address: 'recipient@example.com'
                }
            }
        ]
    },
    saveToSentItems: true
};

// Send request to Graph API
fetch('https://graph.microsoft.com/v1.0/me/sendMail', {
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(emailData)
})
.then(response => {
    if (response.status === 202) {
        console.log('Email sent successfully!');
    } else {
        return response.json().then(err => { throw err; });
    }
})
.catch(error => {
    console.error('Error sending email:', error);
});

For Node.js, use axios (install it first with npm install axios):

const axios = require('axios');

const accessToken = 'YOUR_ACCESS_TOKEN_HERE';
const emailData = { /* same as the browser example above */ };

axios.post('https://graph.microsoft.com/v1.0/me/sendMail', emailData, {
    headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
    }
})
.then(response => {
    console.log('Email sent successfully!');
})
.catch(error => {
    console.error('Error sending email:', error.response.data);
});

Tips to Make Sense of the Docs

  • Skip the C# Examples: Focus on the raw HTTP request sections (they show the method, endpoint, headers, and JSON payload you need—this is universal).
  • Authentication is Non-Negotiable: You can’t use the API without an OAuth2 access token. Spend time setting up an app registration in the Microsoft Azure portal to get these tokens—this is the most common stumbling block.
  • Test with a Tool: Microsoft has a Graph Explorer tool where you can test API requests directly in your browser. This lets you verify payloads and see responses before writing code.

Hope this helps you get unstuck! If you run into issues with authentication or payload formatting, just ask.

内容的提问来源于stack exchange,提问作者ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:44:47