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 = "mysmtp.nowhere.now"
$fileattachment = "c:\\boot.ini"
$from = "hans@nowhere.now"
$to = "somebody@somewhere.org"
$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)
$msg.attachments.add($attachment)
$mailer.send($msg)

7 comments:

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.

Chetan Giridhar said...

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

Function EvtReader {
$logs=System.Diagnostics.EventLog::GetEventLogs("localhost")
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", "127.0.0.1")
$html = $elog.entries[5..10] | ConvertTo-HTML

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

Send-SMTPmail -to jakob@bindslet.dk -from secretuser@somewhere.com -subject errors -smtpserver myserver.com -html -body $html

(http://mspowershell.blogspot.com/2007/12/send-smtpmail-update.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)
$msg.attachments.add($attachment)
}

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

Thanks.

Nikradas said...

Hi,

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

Thanks.
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.

Thanks
Manoj