How to attach a file to an email with PowerShell

前端 未结 5 621
广开言路
广开言路 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:52

    I have experienced such problem, (windows 10 / PS 5.1) My SMTP is not authentified or secure ... I have to finish by this line "MyAttacheObject.Dispose()" ... / and finally that's work :!

    $smtp = new-object Net.Mail.SmtpClient($smtpserver) 
    $attach.Dispose()
    

    this is my code with two attachments :

    # Email configuration NO AUTH NO SECURE
    $emailHost = "smtp.bot.com"
    $emailUser = ""
    $emailPass = ""
    $emailFrom = "myemail@bot.com"
    $emailsTo=@("toyoumylove@bot.com","toyoumybad@bot.com")
    $emailSubject = $title
    $emailbody=$body
    $attachment1 = @($PATh+$outFile) 
    $attachment2 = @($PATh+$inFile) 
    #End of parameters
    
    $msg = New-Object System.Net.Mail.MailMessage
    $msg.from = ($emailFrom)
        foreach ($d in $emailsTo) {    
        $msg.to.add($d)
        }
    $msg.Subject = $emailSubject
    $msg.Body = $emailbody
    $msg.isBodyhtml = $true   
    
    $att = new-object System.Net.Mail.Attachment($attachment1)
    $msg.Attachments.add($att)
    $att = new-object System.Net.Mail.Attachment($attachment2)
    $msg.Attachments.add($att)
    $smtp = New-Object System.Net.Mail.SmtpClient $emailHost
    $smtp.Credentials = New-Object System.Net.NetworkCredential($emailUser, $emailPass);
      $smtp.send($msg)
      $att.Dispose()
    

提交回复
热议问题