简体   繁体   中英

Powershell script to email with attachment from WebRequest Response

I have this command which spits out a pdf file and you can see that it is saving in my C: drive:

$DownloadReportResponse = Invoke-WebRequest -Method Post -Uri $DownloadReportUrl -ContentType "application/json" -Headers $headers -Body $DownloadReportRequestBody -OutFile "C:\Neoload\TestResult-($DateForTestResult).pdf" -TransferEncoding "deflate"

Is there way to script this so it can send the file to certain email address as well?

I have this example script to send email, where would I assign the file so it is attached in the email?

###########Define Variables######## 

$fromaddress = "myGmail@gmail.com" 
$toaddress = "myGmail@gmail.com"
#$CCaddress = "myGmail@gmail.com" 
$Subject = "ACtion Required" 
$body = get-content .\content.htm 
$attachment = $DownloadReportResponse 
$smtpserver = "smtp.labtest.com" 

#################################### 

$message = new-object System.Net.Mail.MailMessage 
$message.From = $fromaddress 
$message.To.Add($toaddress) 
$message.CC.Add($CCaddress) 
$message.Bcc.Add($bccaddress) 
$message.IsBodyHtml = $True 
$message.Subject = $Subject 
$attach = new-object Net.Mail.Attachment($attachment) 
$message.Attachments.Add($attach) 
$message.body = $body 
$smtp = new-object Net.Mail.SmtpClient($smtpserver) 
$smtp.Send($message) 

You can use the build in Send-MailMessage command. Just make sure that the attachment is a path to your file

$EmailSettings=@{
    SMTPServer="smtp.labtest.com"
    From="myGmail@gmail.com" 
    To="myGmail@gmail.com" 
    Subject="ACtion Required" 
    Body=(get-content .\content.htm )
    Attachments="C:\Neoload\TestResult-($DateForTestResult).pdf"
    BodyAsHtml=$true
}
Send-MailMessage @EmailSettings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM