Skip to content

Instantly share code, notes, and snippets.

@gulgulia17
Created May 5, 2023 06:51
Show Gist options
  • Select an option

  • Save gulgulia17/c9b6c02cd7a5ae27c1258422cd90f899 to your computer and use it in GitHub Desktop.

Select an option

Save gulgulia17/c9b6c02cd7a5ae27c1258422cd90f899 to your computer and use it in GitHub Desktop.
<?php
$tenant_id = 'your_tenant_id';
$client_id = 'your_client_id';
$client_secret = 'your_client_secret';
// Get the OAuth access token
$url = "https://login.microsoftonline.com/$tenant_id/oauth2/v2.0/token";
$data = array(
'grant_type' => 'client_credentials',
'client_id' => $client_id,
'client_secret' => $client_secret,
'scope' => 'https://graph.microsoft.com/.default'
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$response = json_decode($result);
$access_token = $response->access_token;
// Connect to the mailbox using IMAP
$host = '{outlook.office365.com:993/imap/ssl}';
$username = 'your_email_address';
$password = 'your_password';
$mailbox = imap_open($host, $username, $password);
// Get the list of emails
$emails = imap_search($mailbox, 'ALL');
// Loop through each email and fetch its details
foreach ($emails as $email_number) {
$email_structure = imap_fetchstructure($mailbox, $email_number);
$header = imap_headerinfo($mailbox, $email_number);
$subject = $header->subject;
$from = $header->fromaddress;
$date = $header->date;
$body = '';
// Check the email structure to get the body text
if (isset($email_structure->parts)) {
foreach ($email_structure->parts as $part) {
if ($part->subtype == 'PLAIN') {
$body = imap_fetchbody($mailbox, $email_number, 1.1);
}
}
} else {
$body = imap_body($mailbox, $email_number);
}
// Output the email details
echo "Subject: $subject<br>";
echo "From: $from<br>";
echo "Date: $date<br>";
echo "Body: $body<br><br>";
}
// Close the mailbox connection
imap_close($mailbox);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment