Sending mail using Powershell

Sending an email in powershell can be done, once more, using .Net Frameword 🙂

Function SendMail([string]$file,[string]$sender,[string]$recipients,[string]$server){

$message = new-object System.Net.Mail.MailMessage

$message.from = $sender

$message.subject = “My first mail in Powershell”

$message.body = “Hello,” + “`r`n” +”This mail was sent automatically by the script” + “`r`n” +”You will find in attachement all information  you asked.” + “`r`n” +”Regards”
foreach ($rec in $recipients){$message.TO.add($rec)}

$attachment = new-object System.Net.Mail.Attachment $file
$message.Attachments.Add($attachment)
$client = new-object System.Net.Mail.SmtpClient $server
$client.Send($message)
$attachment.Dispose()
}

Four parameters aremandatory to get all the power of that function : $fichier, $sender, $recipients, $server.

$file : Contains the exact path of the file to include as attachment. (“C:includesfile.doc”)

$sender : Simply the email address of the sender (“sender@mydomain.com”)

$recipients : Contains a list of recipient with that format :

recipient1@domain.com

recipient2@domain2.com

$server : It is the full name of the server that is allowed to send mails.

Leave a comment