Send email with attachments using PowerShell script

Being able to send emails through script is really useful, particularly for system administrators who often have to administer their servers remotely. It also comes in handy for various other purposes. The code below demonstrates how to send email with attachments using PowerShell.

$smtpServer = "<your smtp mail server address>"
$msg = new-object Net.Mail.MailMessage
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
 
$msg.From = "from@xyz.com"
$msg.To.Add("to@xyz.com")
$msg.Subject = "Your email subject line"
$msg.Body = "Your email body"
 
# Attachments
$file1 = ".\f1.txt"
$file2 = ".\f2.txt"
 
foreach ($file in ($file1, $file2)){
    $att = New-Object Net.Mail.Attachment($file)
    $msg.Attachments.Add($att)
}
 
$smtp.Send($msg)

No comments:

Post a Comment