【发布时间】:2018-07-24 17:00:58
【问题描述】:
我目前正在尝试使用 Microsoft 的 GraphAPI 使用自动 Powershell 脚本发送邮件。
这里是完整的故事:我需要每 15 分钟检查一次 Office 365 邮箱中收到的邮件,获取特定的文件附件(按名称过滤),下载文件,然后用新邮件重新发送。
一切正常,但我无法发送带有附件的新邮件(不带附件的作品)。
这是我的代码:
$date = (get-date).ToUniversalTime().AddMinutes(-15).ToString("yyyy-MM-ddTHH:mm:ssZ")
$Uri = "https://graph.microsoft.com/v1.0/me/messages"
$UriSend = "https://graph.microsoft.com/v1.0/me/sendMail"
$filter = "?`$select=Id,ReceivedDateTime&`$filter=HasAttachments eq true and ReceivedDateTime ge " + $date
$url = $Uri + $filter
$Result = (Invoke-RestMethod -Method Get -Headers $requestheader -Uri $url)
if($Result.value){
## Loop through each results
foreach ($message in $Result.value)
{
# get attachments and save to file system
$query = $Uri + "/" + $message.Id + "/attachments"
$attachments = (Invoke-RestMethod -Method Get -Headers $requestheader -Uri $query)
# in case of multiple attachments in email
foreach ($attachment in $attachments.value)
{
$patternPDF = "FAX AR document\.pdf$"
if($attachment.Name -match $patternPDF)
{
$name = $message.ReceivedDateTime -replace "T","-"
$name = $name -replace "Z",""
$name = $name -replace ":","-"
$path = "c:\Temp\" + $name + ".pdf"
# Creation of the PDF file
$Content = [System.Convert]::FromBase64String($attachment.ContentBytes)
Set-Content -Path $path -Value $Content -Encoding Byte
$file = Get-Content $path -Encoding Byte -ReadCount 0
#Send File by Mail
$body =
@"
{
"message" : {
"subject": "AR Fax",
"body" : {
"contentType": "Text",
"content": "Accusé Fax"
},
"toRecipients": [
{
"emailAddress" : {
"address" : "mail@domain.com"
}
}
],
"attachments":[
{
"@@odata.type":"#microsoft.graph.fileAttachment",
"name":"Fax_AR.pdf",
"contentType":"application/pdf",
"contentBytes":"$file"
}
]
},
"saveToSentItems": "true"
}
"@
# Invokes the request
Invoke-RestMethod -Headers $requestheader -Uri $uriSend -Method Post -Body $body
我在powershell(或一般代码)方面不是很好,所以请放纵^^
编辑:我找到了另一种方法来做我想做的事(我现在打印文件)
【问题讨论】: