[Powershell] – Script to send an email

Click to rate this post!
[Total: 0 Average: 0]
How to send email with Powershell Script ?

It is useful for any Administrator to be able to send an email by script like powershell. For example automatically in the case of a daily report or the control of a task. With or without attachment, to one or more recipients

We can have several cases. In block mode for a simple and punctual sending from a powershell window, or in more detailed script mode

In the first case, in console mode, we will use the Send-MailMessage cmdlet

Send-MailMessage -From “root-helper@mail.com” -To “root-helper@mail.com” -Subject “the subject of my email OK” -SmtpServer “Myserver.smtp.com” -Body “the content of the email” -Attachments “c:\temp\file-to-attach.txt”

Send-mailMessage included to specify a sender, a recipient, an object, a content, a smtp server… In more fraudulent cases (email hack), you can very easily usurp someone’s email address, there is generally no control, especially if you go through a local smtp server. I will do an article on it;)

In a second case, when you really want to write a reusable script, I suggest you use the Net.Mail component.
$SMTPSRV = “Myserver.smtp.com”
$EmailFrom = “sender@mail.com
$EmailTo = @(“recipient@mail.fr,recipient2@mail.fr”)
$subject = “subjet
$body = “content of the email
$File_attachement = “c:\temp\file-to-attach.txt” 
$mailer = new-object Net.Mail.SMTPclient($SMTPSRV)
$msg = new-object Net.Mail.MailMessage($EmailFrom,$EmailTo,$subject,$body)
$msg.IsBodyHTML = $true
$attachement = new-object Net.Mail.Attachment($File_attachement)
$msg.attachments.add($attachment) $mailer.send($msg)


Leave a Reply

Your email address will not be published. Required fields are marked *