How to attach a file to an email with PowerShell

前端 未结 5 657
广开言路
广开言路 2021-01-17 11:23

I have written a PowerShell script that will create an email, however I can\'t seem to attach a file. The file does exist and PowerShell can open it, Could anyone tell me wh

5条回答
  •  死守一世寂寞
    2021-01-17 11:51

    This worked for me using powershell-

    Define Variables:

    $fromaddress = "donotreply@pd.com" 
    $toaddress = "test@pd.com" 
    $Subject = "Test message" 
    $body = "Please find attached - test"
    $attachment = "C:\temp\test.csv" 
    $smtpserver = "mail.pd.com" 
    

    Use the variables in the script:

    $message = new-object System.Net.Mail.MailMessage 
    $message.From = $fromaddress 
    $message.To.Add($toaddress)
    $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)
    

提交回复
热议问题