powershell - 通过 Powershell Graph API 发送带有附件的邮件
问题描述
我目前正在尝试使用 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(或一般代码)方面不是很好,所以请放纵^^
编辑:我找到了另一种方法来做我想做的事(我现在打印文件)
解决方案
我找到了另一种方法来做我想做的事(我现在打印文件)所以我要结束这个话题了。
推荐阅读
- javascript - JavaScript 将 id 与表单输入元素 id 匹配
- java - 简化叉积 foreach 循环 - 也许使用 Lambdas?
- python - python .env 更改保存
- r - R - 在时间序列上循环通过数据框行的距离计算
- javascript - 接收字符串在数据库中保存错误
- c# - 可以将多个需求连接到一个需求处理程序吗?
- php - Laravel 网站使用 (http 500) 响应 Curl/file_get_contents,因此 Google 和 Yandex 机器人无法访问网站
- algorithm - 如何分组旅行路线(设置封面问题)
- php - 从 excel 列表中突出显示网页上的文本
- ruby - 自定义函数中的 Puppet 异常处理 (Puppet+Ruby)