How to send a simple email from a Windows batch file?

前端 未结 6 1553
醉酒成梦
醉酒成梦 2020-12-07 21:35

I\'m running Windows 2003 Service Pack 2. I have a batch file that runs on demand. I want to have an email sent every time the batch file runs. The email is simple, just a s

6条回答
  •  无人及你
    2020-12-07 22:04

    If PowerShell is available, the Send-MailMessage commandlet is a single one-line command that could easily be called from a batch file to handle email notifications. Below is a sample of the line you would include in your batch file to call the PowerShell script (the %xVariable% is a variable you might want to pass from your batch file to the PowerShell script):

    --[BATCH FILE]--

    :: ...your code here...
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  -windowstyle hidden -command C:\MyScripts\EmailScript.ps1 %xVariable%
    

    Below is an example of what you might include in your PowerShell script (you must include the PARAM line as the first non-remark line in your script if you included passing the %xVariable% from your batch file:

    --[POWERSHELL SCRIPT]--

    Param([String]$xVariable)
    # ...your code here...
    $smtp = "smtp.[emaildomain].com"
    $to = "[Send to email address]"
    $from = "[From email address]" 
    $subject = "[Subject]" 
    $body = "[Text you want to include----the 
    is a line feed:

    ]" $body += "[This could be a second line of text]" + "
    " $attachment="[file name if you would like to include an attachment]" send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Attachment $attachment -Priority high

提交回复
热议问题