Wednesday, December 13, 2006

Sending emails from powershell

Here is a small script to send emails from PowerShell. Remember to use a valid SMTP server.

$SMTPserver = ""
$fileattachment = "c:\\boot.ini"
$from = ""
$to = ""
$subject = "PowerShell Test"
$emailbody = "this is my very first email send through PowerShell 1.0"

$mailer = new-object Net.Mail.SMTPclient($SMTPserver)
$msg = new-object Net.Mail.MailMessage($from, $to, $subject, $emailbody)
$attachment = new-object Net.Mail.Attachment($fileattachment)


Jakob Bindslet said...

Add the following line:
$msg.IsBodyHTML = $true

Before the $mailer.send($msg) statement in order to allow HTML content in the email body.

cjgiridhar said...

Thanks..This was useful....I was also trying to:

Function EvtReader {
return $logs
$mail.Body = EvtReader

But I dont get the body in the mail as I desire..Can you help?

Jakob Bindslet said...

How about something like this:

$elog = new-object system.diagnostics.eventlog("system", "")
$html = $elog.entries[5..10] | ConvertTo-HTML

And then use my email script with html option to attach the html:

Send-SMTPmail -to -from -subject errors -smtpserver -html -body $html


Red said...

This is terrific! Just what I needed - thanks. I made one change, because sending an email without an attachment failed, so I wrapped the attachment se4ction in an if statement -
if ($Att -ne $null)
$attachment = new-object Net.Mail.Attachment($fileattachment)

lakbaytaodev said...

Hi Jakob,

I am interested with the mail script but I got this error when trying to execute the script you gave.

Exception calling "Send" with "1" argument(s): "Failure sending mail."
At C:\Users\Tata\testscripts\siyaro.ps1:12 char:13
+ $mailer.send <<<< ($msg)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException


Nikradas said...


How can i use my login and password? Because when i execute an error raised showing me that i wasn't logged.

Marcos Freccia

Manoj Kumar said...

Hi Jakob,

I'm looking for a script which can generate random size (with/without attachment) email traffic to a set of recipients. I am able to send individual mails using your scripts, but haven't succeeded in cutomizing it that way.
please help.