Dec 5 2007

How to send an email using a Windows Powershell script

If you're new here, you may want to start with my most popular posts. Then, subscribe to my RSS feed to stay updated. Thanks for visiting!



Google Query: send email with powershell

In a previous post, I showed you how you can schedule a Powershell script. In this post I show you how to use Powershell to send an email. Thanks to Otto Helweg for the inspiration. This might be useful if you would like an email sent confirming that a script ran successfully.

This can be accomplished by using the Net.Mail.SmtpClient object. The syntax of the Powershell code needed is below:

 

 

 

 

$emailFrom = "user@yourdomain.com"
$emailTo = "user@yourdomain.com"
$subject = "your subject"
$body = "your body"
$smtpServer = "your smtp server"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)

That’s it. Put this code (filling in your appropriate information) at the end of your Powershell script to send an email after the rest of the script finishes processing. If you use this code snippet in any of your projects please feel free to let me know in the comments.

Happy Coding!

Technorati Tags: , , ,

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

TAGS:

48 Comments on this post

Trackbacks

  1. Emails e Powershell « FreeBeing wrote:
  2. Setting up Windows against machine theft wrote:

    [...] 3., To send email from windows try this one: http://www.searchmarked.com/windows/…ell-script.php You need to install powershell on your Windows to get this script running. There is a possibility [...]

    February 16th, 2011 at 3:05 pm
  1. Ivan Versluis said:

    I used this example to schedule a ps1 script and email the output. thanks again!

    December 15th, 2007 at 2:19 pm
  2. hstagner said:

    Hello Ivan,

    I am glad that the example worked for you and it was something that you could use in one of your scripts.

    Thanks for reading!

    Regards,

    Harley Stagner

    December 17th, 2007 at 11:00 am
  3. Leon said:

    Hello Harley

    I use scom2007 and in the monitor console i would like to select an alert and then mail it to our automated ticket system. In the mailbody i should use several parameters from the alert.

    any idea how to handle this? can i use you’re script within the monitor console

    grtz
    Leon

    July 2nd, 2008 at 4:05 pm
  4. hstagner said:

    Hello Leon,

    I have not used scom2007 all that much. However, I do know that it is powershell-enabled. So, you should be able to use the code here with it. I think you will find the information at:

    http://dmitrysotnikov.wordpress.com/2007/03/21/momscom-powershell/

    Useful. Thank you for reading!

    Regards,

    Harley Stagner

    July 2nd, 2008 at 11:28 pm
  5. Nitin Arora said:

    How would you add an attachment?
    Definition : System.Void Send(String from, String recipients, String subject, String body), System.Void Send(MailMessage message)

    In VBScript we can use the CDO.Message object and use the method AddAttachment.

    August 12th, 2008 at 11:45 am
  6. hstagner said:

    Hello Nitin,

    Thank you for reading! I found your answer at Grant Holliday’s Blog

    Here is the code:

    $filename = “logfile.txt”
    $smtpServer = “localhost”

    $msg = new-object Net.Mail.MailMessage
    $att = new-object Net.Mail.Attachment($filename)
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)

    $msg.From = “somebody@yourdomain.com”
    $msg.To.Add(”somebody@theirdomain.com”)
    $msg.Subject = “Nightly Log File”
    $msg.Body = “The nightly log file is attached”
    $msg.Attachments.Add($att)

    $smtp.Send($msg)

    Thanks Grant!

    August 17th, 2008 at 6:50 pm
  7. Gary said:

    There is a mail-alert management pack that may help you. Its not the exact solution you are looking for because you would need to highlight the alert, then right click, enter the address and send it.
    SCOM has its own powershell commands so I believe with this send mail code and some code to find a specific alert you could send it directly to the ticketing system.

    February 4th, 2009 at 9:24 am
  8. Jeffrey Snover said:

    Thanks for posting this. This is super useful stuff and works with both V1 and V2. We decided that this was so important that we decided to ship a cmdlet in V2 to do this:

    Sends an e-mail message.
    Send-MailMessage
    (0)-To
    (1)-Subject | -sub
    -From
    (2)[-Body ]
    (3)[-SmtpServer | -ComputerName ]
    [-Attachments | -PsPath (ByValue)]
    [-Bcc ]
    [-BodyAsHtml | -BAH ]
    [-Cc ]
    [-Credential ]
    [-DeliveryNotificationOption | -DNO ]
    [-Encoding | -BE ]
    [-Priority ]
    [-UseSsl ]

    Keep sharing.

    Experiment! Enjoy! Engage!

    Jeffrey Snover [MSFT]
    Windows Management Partner Architect
    Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
    Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

    February 8th, 2009 at 9:29 pm
  9. hstagner said:

    Wow! Jeffrey Snover. Thanks for reading! It is an honor sir…

    Awesome that it is now going to be a cmdlet. I am currently writing a book on Hyper-V and I was also playing with the new FailoverCluster modules. Very cool stuff indeed. I am looking forward to the official release of V2.

    Regards,

    Harley Stagner

    February 8th, 2009 at 11:06 pm
  10. abdul said:

    Harley-

    I so appreciate this…. I was looking for something like this for weeks… I have one question … I followed what you wrote for Nitin ..but I tweaked it for Exchange mailbox stats….

    Get-MailboxStatistics -Server mailbox01 | Sort-Object TotalItemSize -Descending | Select DisplayName, MailboxGUID, ItemCount, @{expression={$_.totalitemsize.value.ToMB()}}, DatabaseName | Export-CSV mailbox01.csv

    $filename = “mailbox01.csv”
    $smtpServer = “hubserver”

    $msg = new-object Net.Mail.MailMessage
    $att = new-object Net.Mail.Attachment($filename)
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)

    $msg.From = “admin”
    $msg.To.Add(”admin”)
    $msg.Subject = “Nightly Log File”
    $msg.Body = “The nightly log file is attached”
    $msg.Attachments.Add($att)

    $smtp.Send($msg

    the question I have when the output file is created it goes automatically to my admin folder on the server…is there a way to put it in another folder? because the script and the attachment has to be in the same admin folder in order for it to work…

    and another question..well more of help in terms of guidance..where did you start learning powershell.. I want to this for my Exchange and AD environments and I am really confused as to where to start …I am beginner…so if you can help navigate this noob…which books to read…and to start from.. it will be much appreciated… and keep up the good work and sharing…thanks.

    March 3rd, 2009 at 9:22 pm
  11. hstagner said:

    Hello abdul,

    First, thanks for reading!

    You could try giving the full path to the folder you want the export file to be stored in.

    c:\somepath\somefolder\mailbox01.csv

    As for your second question, I learned/am learning by doing projects at work and using the internet. For a good background (on the language itself) book, I would recommend “Windows PowerShell in Action”. For an excellent practical book, I would recommend “Pro PowerShell.”

    I hope that this helps.

    Regards,

    Harley Stagner

    March 5th, 2009 at 10:53 am
  12. Brandon said:

    I use this code in conjunction with performance counters so that I recieve an email alert anytime a threshold is reached. Thanks!

    June 17th, 2009 at 10:44 am
  13. hstagner said:

    You are quite welcome! I am glad that you were able to use this. Thank you for reading!

    June 17th, 2009 at 12:41 pm
  14. Coleman said:

    I used this code to email the results of a script that I setup to send me the free disk space on my servers, Thanks

    July 24th, 2009 at 12:33 pm
  15. eddie korbs said:

    Hello, created an automated test and wanted the results mailed to myself and others in my group. Vaarryyy niiiceeee sir…

    September 14th, 2009 at 4:20 pm
  16. TomasH said:

    Hi, first thank you for this helpful topic and useful script. Unfortunatelly I have a small problem with attachment or in fact with this file after the *.PS1 script finish.
    I generate a text file during the script and then at the end of the script I send it via these script-lines v2 and it works. I get email with attachment.
    But then I’m not able to modify or delete this sent file until I close whole powershell. I get error message that another process uses this file.
    Any advice?

    October 14th, 2009 at 4:24 am
  17. TomasH said:

    Small update:
    1) this file is on network drive f.ex. \\server1\share$
    2) i checked it by process explorer, and there is information who keeps this file.
    powershell.exe 2448(PID) Handle \device\LanmanRedirector\server1\share$\servermonitor\temp\message.txt

    I can kill this handle, then I can delete the file and powershell is still usable. But it is not the best way.

    October 14th, 2009 at 4:46 am
  18. hstagner said:

    Hello TomasH,

    Can you send me the code that you have written? Thank you for reading!

    October 14th, 2009 at 7:53 am
  19. TomasH said:

    Hi, wow you work since morning :-) ))

    here is the last part of the script. Before this, some FOR-cyclus write messages into the file message.txt
    If I delete whole this mailing-part, the deleting by “RM” works fine.

    ~
    $workpath = “\\Server1\share$\servermonitor”
    $filename = “$workpath\temp\message.txt”
    $smtpServer = “sv057089”

    $msg = new-object Net.Mail.MailMessage
    $att = new-object Net.Mail.Attachment($filename)
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)

    $msg.From = “servermonitor@mydomain.com”
    $msg.To.Add(”tomas.hyps@mydomain.com”)
    $msg.Subject = “SERVERS-UPTIME-Morning report”
    $msg.Body = “The nightly log file is attached”
    $msg.Attachments.Add($att)

    $smtp.Send($msg)

    write.host “Message has been sent.” -fore green

    rm $workpath\temp\message2.txt
    }
    this is the real end of the file.

    Thank you in advance for a help.

    October 14th, 2009 at 8:14 am
  20. hstagner said:

    Hello TomasH,

    I believe that the attachment is being held open. Try this to close the attachment after you send it:

    $att.Dispose()

    at the end of the script.

    I hope this helps. Thank you again for reading!

    October 14th, 2009 at 11:08 am
  21. TomasH said:

    You’re right Harley.
    Thx a lot for your help.

    Cheers
    Thomas

    October 15th, 2009 at 12:59 am
  22. Allen said:

    I’m thrilled to see some PowerShell book recommendations, but which book is “Pro PowerShell”? I found three with the “Pro Windows PowerShell…” title.
    Pro Windows PowerShell (Paperback) by Hristo Deshev
    Professional Windows PowerShell (Programmer to Programmer) by Andrew Watt
    Professional Windows PowerShell for Exchange Server 2007 Service Pack 1 (Programmer to Programmer) by Joezer Cookey-Gam, Brendan Keane, Jeffrey Rosen, and Jonathan Runyon

    Thanx!

    October 23rd, 2009 at 12:36 pm
  23. arenas said:

    hello to all :)

    your script is so helpful!

    i gat this error:
    Exception calling “Send” with “1″ argument(s): “Échec d’envoi du courrier.”
    à : ligne:1056 caractère:10
    + $smtp.Send <<<< ($msg)

    ps
    i have us "live.fr". and for the smtp i use : $smtpServer = “smtp.live.com”
    also i need to handle the "port 25"!

    how i have to do?
    many thx for you help
    arenas

    November 13th, 2009 at 12:52 pm
  24. Mi.Ke. said:

    Hi Harley,

    I want to use this code to send a mail after a
    GET-USER -Filter …. | MOVE-MAILBOX …..
    Every User should receive a mail at to be informed that his mailbox has been transferred to the new server (f.i. from 2003 –> 2007)

    Any idea how to get this work ?

    Thx – Regards Mi.Ke.

    February 9th, 2010 at 1:41 am
  25. Igor said:

    I am having some trouble.
    Here is my code. I have edited out the domains of course and I am usign 2 variables.

    $args[0] = $site
    $args[1] = $site2

    $emailFrom = “user@domain.com”
    $emailTo = “user2@domain.com”
    $subject = “The $site has been deployed”
    $body = “The $site has been deployed ”
    $smtpServer = “smtp.domain.com”
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)

    I execute it with the following error:
    PS O:\Test> .\email.ps1 test test
    Exception calling “Send” with “4″ argument(s): “The SMTP server requires a secure connection or the client was not auth
    enticated. The server response was: 5.7.1 Client was not authenticated”
    At O:\Test\email.ps1:10 char:11
    + $smtp.Send( <<<< $emailFrom, $emailTo, $subject, $body)
    $smtp.Send($emailFrom, $emailTo, $subject, $body)

    February 22nd, 2010 at 2:09 pm
  26. mihir said:

    i am getting following email
    exception calling “send” with “4″ argument(s): “Mailbox unavailable.The server response was:5.0.0 access denied”.

    This account is working fine in sql server but i am getting this error in powershell

    February 23rd, 2010 at 9:57 am
  27. tony said:

    I used your example to create a useful multi-purpose script that will generate the body of the email from either a pipe or an argument.
    Thanks for the example to get me started.

    param($emailto, $subject, $body)
    begin {
    $smtpServer = “oursmtpserver”
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $emailFrom = “PowerShellScript@ourdomain.com”

    $etext = “”
    if ($body) {
    $etext= $body -join “`r`n”
    }
    }
    Process {
    $etext += “$_`r`n”
    }

    end{
    if ($etext) {
    $smtp.Send($emailFrom, $emailTo, $subject, $etext)
    }
    }

    May 6th, 2010 at 12:17 pm
  28. Gabriel_C said:

    Hi everyone the script is (like other guys said) very usefull, thanks, but I have another question, what is the syntax if I want that the attachment be a part of message body, like an image?

    June 1st, 2010 at 8:02 pm
  29. sathish said:

    How to Send HTML Tags via SMPTCLIENT

    July 14th, 2010 at 5:24 am
  30. mark_h said:

    I’m startin to convert my scripts from fugly batch to powershell. Used your code, worked for me, thanx!

    (I’m beginnin to like posh… =)

    July 19th, 2010 at 12:11 pm
  31. MoreThanWYSIWYG said:

    Hi, I am trying to set up a test email ps script.

    I use the following :

    $emailFrom = “ddddd$aaaaaa.com”
    $emailTo = “ddddd$aaaaaa.com”
    $subject = “Test email from powershell”
    $body = “testtest”
    $smtpServer = “smtp.ccccc.com”
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $smtp.Send($emailFrom, $emailTo, $subject, $body)

    Here are the results:

    Exception calling “Send” with “4″ argument(s): “Failure sending mail.”
    At C:\PowerShellScripts\sendmail.ps1:7 char:11
    + $smtp.Send <<<< ($emailFrom, $emailTo, $subject, $body)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    August 9th, 2010 at 10:09 am
  32. MoreThanWYSIWYG said:

    Any help would be greatly appreciated.

    Thanks,
    Joe

    August 9th, 2010 at 10:10 am
  33. marcos said:

    quisiera saber línea por línea qué hace el siguiente script de powershell:

    $contenido = Get-Content -Path “D:\Scripts\fin.txt”
    $mensaje = Get-Date -Format dd/MM/yy
    $mensaje = $mensaje + ” – ”
    if ($contenido -match “Exito”)
    {
    $mensaje = $mensaje + “El respaldo de POSTGRES termino correctamente”
    }
    else
    {
    $mensaje = $mensaje + “El respaldo de POSTGRES NO termino correctamente”
    }
    Send-MailMessage -SmtpServer 192.168.1.20 -From monitor@miweb.com -To monitoreo@miweb.com -Subject “Respaldo 123_postgres” -Body $mensaje
    Remove-Item -Path D:\Scripts\fin.txt

    muchas gracias por la ayuda
    Marcos

    December 3rd, 2010 at 11:41 am
  34. Scott Alvarino said:

    Great example and thankyou. How do you like the send-mailmessage cmdlet. check out how i am using it here.
    http://techjunkie.tv/how-to-use-send-mailmessage-with-a-password-in-powershell-script

    Let me know what you think about this code.
    My Twitter is http://twitter.com/scottalvarino

    December 29th, 2010 at 10:11 am
  35. Scott Alvarino said:

    Marcos I can help you with this but I need the script in English. But I will try anyways let me que tu piensa, nice spanish huh.
    $contenido = Get-Content -Path “D:\Scripts\fin.txt” #get content from file
    $mensaje = Get-Date -Format dd/MM/yy # make date in this format
    $mensaje = $mensaje + ” – ” #make variable with that variable
    if ($contenido -match “Exito”) # if you have a match of Exit then do the rest
    {
    $mensaje = $mensaje + “El respaldo de POSTGRES termino correctamente”
    }
    else
    {
    $mensaje = $mensaje + “El respaldo de POSTGRES NO termino correctamente”
    }
    Send-MailMessage -SmtpServer 192.168.1.20 -From monitor@miweb.com -To monitoreo@miweb.com -Subject “Respaldo 123_postgres” -Body $mensaje
    Remove-Item -Path D:\Scripts\fin.txt # delete el file

    December 29th, 2010 at 10:17 am
  36. jorge said:

    respaldo

    January 12th, 2011 at 3:43 pm
  37. Andbac said:

    Perhaps abit late…but anyhow:

    A note regarding the -Encoding parameter in the Send-MailMessage in the (V2) cmdlet: it will not accept ASCII, UTF8 etc as value. One have to create a encoding object first like this (in my case UTF8):

    $enc = New-Object System.Text.utf8encoding

    Which then can be used like this:

    Send-MailMessage -to “Firstname Lastname ” -From “Firstname2 Lastname2 ” `
    -Subject “Test mail from PowerShell” -Body “Sending mail trough PowerShell V2 Send-MailMessage cmdlet” `
    -SmtpServer mailserver.domain.com -Encoding $enc

    March 31st, 2011 at 3:31 am
  38. Bike Storage said:

    Windows PowerShell is Microsoft’s task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework.

    June 8th, 2011 at 1:05 am
  39. Clayton said:

    This script has come in handy.

    I’ve been using this on all my scripts to email myself the log files.

    June 21st, 2011 at 11:35 am
  40. thb said:

    great help!

    August 18th, 2011 at 2:37 am
  41. anirudh said:

    i have tried sending mails to my gmail account using the first script but it didnt work it gave the following error:

    Exception calling “Send” with “4″ argument(s): “Mailbox unavailable. The server response was: 5.7.1
    Unable to relay”

    Looking at the error i thougt it might work for sending mails to an internal address and yeah it worked.

    is there a way i can modify the below script to use it to send mails to external domains:
    $emailFrom = “user@yourdomain.com”
    $emailTo = “user@yourdomain.com”
    $subject = “your subject”
    $body = “your body”
    $smtpServer = “your smtp server”
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $smtp.Send($emailFrom, $emailTo, $subject, $body)

    September 14th, 2011 at 10:45 am
  42. anirudh said:

    i have found the problem. i need to authenticate the sender to send mails to external domains.
    the below script worked for me to send mails to external domains:
    $emailFrom = “user@yourdomain.com”
    $emailTo = “user@yourdomain.com”
    $subject = “your subject”
    $body = “your body”
    $smtpServer = “your smtp server”
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $credentials=new-object system.net.networkcredential(”domain\username”,”password”)
    $smtp.credentials=$credentials.getcredentials($smtpserver,”portno(25 in my case)”,”authenticationtype(basic in my case)”)
    $smtp.Send($emailFrom, $emailTo, $subject, $body)

    September 16th, 2011 at 7:03 am
  43. Darin said:

    Do you know of a way to set a reminder in Outlook using this script? I’m trying to send an smtp html email and have it automatically set a reminder for each of the users.

    Thanks!

    October 12th, 2011 at 12:04 pm
  44. mahmoud said:

    isn’t this lighter and better ??

    $messageParameters = @{
    smtpServer = “smtphost”
    From = [string]$from
    To = [string]$to
    Subject = “You Submitted a Job”
    Body = “Your Job Chain is submitted successfully”
    }
    Send-MailMessage @messageParameters -BodyAsHtml

    November 8th, 2011 at 7:10 pm
  45. mahmoud said:

    or this way

    $messageParameters = @{
    smtpServer = “smtphost”
    From = md@yahoo.com
    To = md@yahoo.com
    Subject = “You Submitted a Job”
    Body = “Your Job Chain is submitted successfully”
    }

    November 8th, 2011 at 7:12 pm
  46. Paul said:

    Thanks, works great.
    I try to mail to 5000 recipients, is there a way the script can read from a textfile or excell file. Then I can mail those people an attachment.

    Thank you

    December 7th, 2011 at 8:06 am

LEAVE A COMMENT

Subscribe Form

Subscribe to Blog

Sponsors

Recent Readers

JOIN MY COMMUNITY!
                  Computers Blogs - Blog Top Sites