Мне нужно иметь возможность получать сообщения электронной почты для нескольких определенных получателей внутри отправленных элементов. Когда я запускаю свой код, я получаю error bad request error 400
. Я просматриваю каждого получателя, письма которого мне нужны. Цель состоит в том, чтобы ввести несколько адресов электронной почты получателей, которым я отправил электронные письма, затем получить электронные письма и сохранить их в CSV.
Ошибка присутствует в конечной точке запроса, моей конечной точке.
$nextLink = "https://graph.microsoft.com/v1.0/users/${mailuser}/mailFolders/SentItems/messages?`$filter=(sentDateTime ge ${startDate})&`$search='to:${recipientUser}'&`$select=sentDateTime,subject,toRecipients,bodyPreview,ccRecipients"
Ниже приведен весь код.
# Azure AD app registration details
$appId = ""
$appSecret = ""
$tenantId = ""
# User to retrieve mail sent messages(your email, since you're the sender)
$mailuser = "[email protected]"
# User email addresses that you sent emails to, separated by commas
$recipientUsers = "[email protected]", "[email protected]"
# Date range for filtering emails
$startDate = '2022-01-01T00:00:00Z'
# Define the folder path to store the results
$tempFolderPath = "C:\Temp"
# Check if the folder exists, if not, create it
if (-not (Test-Path $tempFolderPath)) {
New-Item -Path $tempFolderPath -ItemType Directory -Force
}
# Define CSV file path
$csvFilePath = "$tempFolderPath\sentitemsemail_data2.csv"
# Define API endpoint and parameters for authentication
$authEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$authBody = @{
client_id = $appId
client_secret = $appSecret
scope = "https://graph.microsoft.com/.default"
grant_type = "client_credentials"
}
# Define function to get request headers for Graph API
function Get-RequestHeaders {
$tokenResponse = Invoke-RestMethod -Method Post -Uri $authEndpoint -Body $authBody
$accessToken = $tokenResponse.access_token
@{
'Authorization' = "Bearer $($accessToken)"
'Accept' = 'application/json'
}
}
# Define function to retrieve messages
function Get-Messages {
param (
[string]$url
)
$requestHeaders = Get-RequestHeaders
Invoke-RestMethod -Method Get -Uri $url -Headers $requestHeaders
}
# Define function to export email object to CSV
function Export-EmailObjectToCSV {
param (
[object]$emailObject
)
$emailObject | Export-Csv -Path $csvFilePath -Append -NoTypeInformation
}
# Loop through each recipient user
foreach ($recipientUser in $recipientUsers) {
# Initialize $nextLink variable with the initial endpoint URL, from $startDate to current date
$nextLink = "https://graph.microsoft.com/v1.0/users/${mailuser}/mailFolders/SentItems/messages?`$filter=(sentDateTime ge ${startDate})&`$search='to:${recipientUser}'&`$select=sentDateTime,subject,toRecipients,bodyPreview,ccRecipients"
# Loop until all pages are fetched
do {
# Retrieve messages for the current page
$messages = Get-Messages -url $nextLink
# Loop through each message
foreach ($message in $messages.value) {
$subject = $message.subject
$sentdatetime = $message.sentDateTime
$bodyPreview = $message.bodyPreview
# Initialize an array to store all CC recipient addresses
$ccRecipientAddresses = New-Object System.Collections.ArrayList
foreach ($recipient in $message.toRecipients) {
$recipientName = $recipient.emailAddress.name
$recipientAddress = $recipient.emailAddress.address
# Loop through each CC recipient and store their address
foreach ($torecipient in $message.ccRecipients){
[void]$ccRecipientAddresses.Add($torecipient.emailAddress.address)
}
# Create a new object to store the data
$emailObject = [PSCustomObject]@{
Subject = $subject
RecipientName = $recipientName
RecipientAddress = $recipientAddress
ToRecipientAddresses = $ccRecipientAddresses -join ", "
SentDateTime = $sentdatetime
BodyPreview = $bodyPreview
}
# Export each email object to the CSV file
Export-EmailObjectToCSV -emailObject $emailObject
}
}
# Check if there are more pages to fetch
if ($messages."@odata.nextLink") {
$nextLink = $messages."@odata.nextLink"
}
else {
$nextLink = $null # If no more pages, exit the loop
}
} while ($nextLink)
}
можешь опубликовать решение, приятель?
Вы не можете комбинировать параметры запроса $filter
и $search
для messages
.
Фильтр можно переместить в параметр запроса $search
. Значение поиска должно быть заключено в двойные кавычки.
GET /v1.0/users/${mailuser}/mailFolders/SentItems/messages?$search = "to:${recipientUser} AND sent>=${startDate}"&$select=sentDateTime,subject,toRecipients,bodyPreview,ccRecipients
ПС
$nextLink = "https://graph.microsoft.com/v1.0/users/${mailuser}/mailFolders/SentItems/messages?&`$search = ""to:${recipientUser} AND sent>=${startDate}""&`$select=sentDateTime,subject,toRecipients,bodyPreview,ccRecipients"
Брат мой, большое спасибо за исправление. это сработало. еще один запрос, если мне нужно запросить папку «Входящие», внутри поискового запроса, могу ли я изменить поиск вот так $search = ""from:${senderUser} AND receive>=${startDate}""
?
я создал что-то подобное для папки «Входящие» и получаю ошибку 404, но пользователи в цикле существуют$nextLink = "https://graph.microsoft.com/v1.0/users/${mailuser}/mailFolders/Inbox/messages?&`$search = ""from:${senderUser} AND received>=${startDate}""&`$select=receivedDateTime,subject,bodyPreview"
Не могли бы вы поделиться кодом ошибки и сообщением об ошибке, которое должно быть частью ответа.
Привет, приятель, это сработало. Я указал неправильный исходный адрес, то есть владелец почтового ящика был неправильным. Я изменил и теперь могу экспортировать электронные письма в папку «Входящие» так же, как отправленные. Ваш ответ действительно сработал. Большое спасибо.
Да, вы можете получать электронные письма. Попробуйте снять фильтр. Затем добавляйте элементы фильтра по одному, чтобы найти фактическую ошибку. Я считаю, что одинарные кавычки нужно экранировать 'to:${recipientUser}'