Emailing script results

You may want to send an email with results of WinSCP transfer (or other operation). First, you need to check WinSCP exit code to determine if the script succeeded or not.

To actually send the email, you can use:

  • PowerShell Send-MailMessage cmdlet or
  • Any command-line email client you like, e.g. sendmail or blat.

PowerShell Send-MailMessage

The following batch file launches PowerShell to use its Send-MailMessage cmdlet. With Send-MailMessage, it is easy to send WinSCP log file as an attachment.

@echo off
set WINSCP_LOG=example.log
rem Run WinSCP script /ini=nul /log=%WINSCP_LOG% /script=example.txt
rem Check WinSCP result and prepare the email message
if %ERRORLEVEL% equ 0 (
    set WINSCP_SUBJECT=Success
    set WINSCP_MESSAGE=The files were uploaded successfully.
    set WINSCP_CODE=0
) else (
    set WINSCP_SUBJECT=Error
    set WINSCP_MESSAGE=Error uploading files, see attached log.
    set WINSCP_CODE=1
rem Send the email message
set SMTP_PASSWORD=password
if exist "%WINSCP_LOG%" set ATTACHMENT=-Attachments '%WINSCP_LOG%'
powershell -ExecutionPolicy Bypass -Command Send-MailMessage ^
    -From %SMTP_FROM% -To %SMTP_TO% -Subject '%WINSCP_SUBJECT%' -Body '%WINSCP_MESSAGE%' ^
    %ATTACHMENT% -SmtpServer %SMTP_SERVER% -UseSsl ^
    -Credential (New-Object System.Management.Automation.PSCredential ^
        ('%SMTP_USERNAME%', (ConvertTo-SecureString '%SMTP_PASSWORD%' -AsPlainText -Force)))
exit /b %WINSCP_CODE%

Of course, once you rely on PowerShell anyway, it might be better to use PowerShell for your whole script, instead using a batch file. In PowerShell you can even use WinSCP .NET assembly, what gives you much better error control among other things.


Download and install the sendmail. When installing sendmail, you can ignore all references to /usr/lib/ (or c:\usr\lib) directories in its installation instructions, as you will be running sendmail.exe directly from a Windows batch file. Just place all sendmail files (sendmail.exe, sendmail.ini, libeay32.dll and ssleay32.dll) to any convenient location (e.g. along with WinSCP), and edit the sendmail.ini.

An example of using sendmail with WinSCP: /ini=nul /log=example.log /script=example.txt
if %ERRORLEVEL% equ 0 (
  echo Success
  sendmail.exe -t < success_mail.txt
  exit /b 0
) else (
  echo Error!
  sendmail.exe -t < error_mail.txt
  exit /b 1

The contents of success_mail.txt may for example be:

Subject: Success

The files were uploaded successfully.

Last modified: by martin