Skip to main content

Robocopy with SMTP Status

When you need to copy files reliably on Windows, Robocopy (Robust File Copy) is one of the most powerful built-in tools. But wouldn’t it be nice to automatically get an email telling you whether the copy job succeeded or failed?

That’s exactly what the script below does. It uses Robocopy to copy files and folders, logs the results, then sends an email notification based on whether the copy completed successfully or not. Let’s break it down step by step.

$Source = "C:\Source"
$Dest   = "D:\Dest"
$Log    = "C:\robocopy.log"
 
 
$SmtpServer = "SmtpServer"
$SmtpPort   = 465
$Username   = "Username"
$Password   = "Password"
$From = "[email protected]"
$To   = "[email protected]"
 
 
Write-Host "Starting Robocopy from $Source to $Dest ..."
& robocopy $Source $Dest /E /COPYALL /R:0 /W:0 /ETA /V /LOG+:$Log
$ExitCode = $LASTEXITCODE
 
 
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($Username, $SecurePassword)
 
 
if ($ExitCode -le 3) {
    Send-MailMessage -From $From -To $To -Subject "Robocopy Completed" -Body "Robocopy finished successfully. Exit code: $ExitCode. See log at $Log" -SmtpServer $SmtpServer -Port $SmtpPort -UseSsl -Credential $Cred
    Write-Host " Robocopy completed successfully. Email sent."
} else {
    Send-MailMessage -From $From -To $To -Subject "Robocopy Failed" -Body "Robocopy failed. Exit code: $ExitCode. See log at $Log" -SmtpServer $SmtpServer -Port $SmtpPort -UseSsl -Credential $Cred
    Write-Host " Robocopy failed. Email sent."
}

Here’s what the key switches mean:

  • /E → Copy all subfolders (including empty ones).
  • /COPYALL → Preserve all file information (timestamps, permissions, attributes, etc.).
  • /R:0 → Don’t retry failed copies.
  • /W:0 → No wait time between retries.
  • /ETA → Show estimated time of arrival for each file.
  • /V → Verbose output.
  • /LOG+:$Log → Append results to the log file.