Tuesday, 20 March 2012

Sending SharePoint system notification e-mails using PowerShell

The script in this article demonstrates an example of how you could use PowerShell to send system notification e-mails to administrators on a scheduled basis. Of course, there are a number of ways to do this sort of thing, including SharePoint workflows, Microsoft SCOM, and custom code. I’m not saying PowerShell is necessarily better than these methods, but I like the flexibility it brings, and as you have full access to the Object Model, you could send notifications from all sorts of areas – for example, successes and errors from the crawl logs, information from the User Profile service application, timer jobs with last run times, list items, site users, etc.

The example I have chosen here is to send an HTML e-mail listing the currently active items from the SharePoint Health Analyzer. This information is effectively just stored in a SharePoint list on the Central Administration site, so I will need to access the list, query the active items and send this information using the SMTP mail server and reply addresses specified in the farm outbound e-mail settings.


First of all we need to get the Central Administration web application and site objects from the farm. Note that we do not need to specify any URLs here - The command will automatically find Central Administration using options provided in the SharePoint 2010 cmdlets:

#Get Central Admin Web Application and Web objects
$caWebApp = (Get-SPWebApplication -IncludeCentralAdministration) | ? { $_.IsAdministrationWebApplication -eq $true }
$caWeb = Get-SPWeb -Identity $caWebApp.Url

Next we can specify the user or group e-mail address that will receive the message, followed by the sender’s e-mail address and the name of the SMTP server sending the message, which I am taking from the farm outbound e-mail settings stored in the Central Administration web application. If you want to send the message to more than one user or group, you could set up an array and walk through each item.

#Set up from, to and server addresses
$toAddress = "svc_installsp2010@domain2010.lab"
$fromAddress = $caWebApp.OutboundMailReplyToAddress
$serverAddress = $caWebApp.OutboundMailServiceInstance.Server.Address

The following part of the script gets the Health Analyzer list (internal name “HealthReports”) and the default display form URL. We need this URL later when configuring hyperlinks in the HTML, so that users can click on a health report directly from the e-mail to show it in the browser.

#Get Health Analyzer list on Central Admin site
$healthList = $caWeb.GetList("\Lists\HealthReports")
$displayFormUrl = $caWeb.Url + ($healthList.Forms | where { $_.Type -eq "PAGE_DISPLAYFORM" }).ServerRelativeUrl

This is probably the trickiest part of the script as it uses a CAML query to find all items in the Health Analyzer, except for those with the Severity column set to “4 – Success”. In other words, it queries any item that the Health Analyzer considers to be a problem on the farm. The CAML itself is specified in the first line below – I’m not going to go into how to write this stuff as there are quite a number of references available on the Internet already.

$queryString = "<Where><Neq><FieldRef Name='HealthReportSeverity' /><Value Type='Text'>4 - Success</Value></Neq></Where>"
$query = New-Object Microsoft.SharePoint.SPQuery
$query.Query = $queryString
$items = $healthList.GetItems($query)

This next section creates the subject and HTML body for the e-mail message. If you know HTML then you will see what is happening, and if you don’t then that’s another subject for you to learn! The key part from a SharePoint perspective is the foreach ($item in $items) routine, as this is where the script walks through each list item found from the query above and injects the column values into the HTML. Note where the $displayFormUrl variable is used from earlier to set up the URL used for the hyperlink. I’m also using the built-in ConvertTo-Html PowerShell cmdlet to format the HTML.

#Set up e-mail message subject and HTML body
$msgTitle = "Health Analyzer results for farm " + $caWebApp.Farm.Name + " - " + (Get-Date)
#HTML head
$head = "<style type=`"text/css`">.tableStyle { border: 1px solid #000000; }</style>"
$head = $head + "<Title>$msgTitle</Title>"
#Create HTML body by walking through each item and adding it to a table
$body = "<H2>$msgTitle</H2><table cellspacing=`"0`" class=`"tableStyle`" style=`"width: 100%`">"
foreach ($item in $items)
    $itemUrl = $displayFormUrl + "?id=" + $item.ID
    [array]$itemValues = @($item["Severity"], $item["Category"], $item["Explanation"], $item["Modified"])
    $body = $body + "<tr>"
    $body = $body + "<td class=`"tableStyle`"><a href=`"" + $itemUrl + "`">" + $item.Title + "</a></td>"
    $itemValues | ForEach-Object {
        $body = $body + "<td class=`"tableStyle`">$_</td>"
    $body = $body + "</tr>"
$body = $body + "</table>"
#Create message body using the ConvertTo-Html PowerShell cmdlet
$msgBody = ConvertTo-Html -Head $head -Body $body

Finally, the commands below use the System.Net.Mail .NET class to send the e-mail, using the IsBodyHtml boolean property to ensure it goes as an HTML message.

#Create e-mail message object using System.Net.Mail class
$msg = New-Object System.Net.Mail.MailMessage($fromAddress, $toAddress, $msgTitle, $msgBody)
$msg.IsBodyHtml = $true
#Send message
$smtpClient = New-Object System.Net.Mail.SmtpClient($serverAddress)

That’s it! The e-mail will be sent when the script is run and should look similar to the one shown below. As you can see, the items in the e-mail match up to the items shown in the Health Analyzer screenshot at the beginning of this article.


You can use Task Scheduler in Windows if you want to send the e-mail on a scheduled basis. Please see this article for more details on how to use Task Scheduler for running PowerShell scripts with SharePoint.


  1. Thanks! Your scripts continue to work without any modifications. I appreciate that for a newbie

  2. Thank you so much Phil! Your scripts saves lot of time!

    Thanks & Regards,
    Salaudeen Rajack's SharePoint Diary

  3. Great script, thanks for the inspiration.

  4. Kindly provide script for search crawl log, user profile as well

  5. Exactly what I needed. One nit pick -- those are supposed to be forward slashes for the list path, correct? Thanks so much for making this available.

  6. article was very nice and helpful at all for me, and pardon me permission to share articles. May be useful Obat tradisional infeksi ginjal :)

  7. When I forward the health results to my team mates, while opening it, they're getting wrong from email address.

    I receive the alert from right email......@abc.com but the same report forwarding to others, they get like alert was sent from .......@xyz.com, what could be reasons, appreciate the fix.

  8. Articles that you provide a very interesting and very useful for me, thank you very much admin and pardon me permission to share the article here : Cara menyembuhkan vertigo

  9. articles that you provide very helpful and helped me hopefully more successful future and many who visit, sorry permission to share the article here: Cara menyembuhkan hepatitis a

  10. thank u somuch many admins are already sharing information with and us, and pardon me permission to share articles herein may be useful for everything : cara menyembuhkan anemia

  11. I can feel that the articles contained in this blog is so interesting. I also get a variety informasin, thanks.
    obat maag terlaris, 100% ampuh mengobati maag akut dan kronis

  12. شركة قمة الدقة للخدمات المنزلية جوده واقل اسعار مع ضمان الخدمه بالاضافة الى الخبرة فى مجال التنظيف بالجبيل وهذا ما يميزنا شركة تنظيف مجالس بالجبيلمن اهم الشركات المتواجده فى الاسواق فنحن متخصصين فى خدمات التنظيف بشكل عام ونهدف الى شركة قمة الدقةلتنظيف منازل بالجبيل بتوفير خدمات تنظيف المنزل المختلفة , ويمكنك التعرف على أهم أعمالنا في تنظيف المنازل وهي شركة تنظيف موكيت بالجبيل تعمل الشركة جاهدة علي توفير العمالة المميزة التي تساعد في انجاز جميع المهام
    شركة قمة الدقة للتنظيف تقدم كافة اعمال تنظيف المنازل والبيوت والشقق والفلل والمجالس والمسابح باعلي جودة ممكنة وارخص الاسعار شركة تنظيف كنب بالجبيل الجميع يعانون من عدم النظافه , بالرغم من انهم يقومون بأعمال التنظيف ولكن يتعبون جدا
    شركة قمة الدقة للنظافة لكثير من الاعتبارات اهمها الدقة فى التنفيذ الترتيب واعادة شركة تنظيف سجاد بالجبيل أن لديها فريق عمل متكامل من العاملين والعاملات الذين يقومون بتنظيف كل المنازل و كل البيوت و كل الأماكن التي تحتاج إلى تنظيف فان خبره.
    شركة قمة الدقة للخدمات المنزلية أصبح التنظيف متعة وتحقيقه امرا سهلا ومتاح فاذا كنت تنزعج من ضيق الوقت أو عدم قدرتك على التنظيف أو حتى إذا كنت شركة تنظيف مساجد بالجبيل تعتبر النظافة بالنسبة للانسان من اهم عوامل الحياة الصحية

  13. الشركة الاولى في مجال التنظيف ومكافحة الحشرات شركة شاها المثالية والتى توجد في المنطقة الشرقية ولها فرع اخر فى المنطقة شركة السفير المثالي .
    خبرة تتعدى ال 25 عاما .
    لديها عمالة ماهرة تتولى مهام التنظيف وعمالة متخصصة في مجال مكافحة الحشرات .
    هاتان الشركتان هما الشركات الاولى في المجال حيث لديهما
    عمالة ماهرة في مجال مكافحة الحشرات بتصريح من وزارة الصحة فلا تقلق عزيزي العميل ويمكن
    الان ان تتعرف على خدماتنا من خلال زيارة الخدمات الاتية كل ما عليك هو الضغط على الخدمة التى تريد ان تط مباشرة تعرف عليها وسوف يرسلك الرابط
    الى الخدمة فورا كل ما عليك الان هو الاتصال بنا على الارقام التالية :
    شركة المثالية للتنظيف بالجبيل
    شركة المثالية للتنظيف بالخبر
    شركة المثالية للتنظيف بالقطيف
    شركة امست للتنظيف
    شركة المثالية للتنظيف بالدمام
    شركة مكافحة الحمام بالدمام
    شركة تنظيف بالقطيف
    شركة تنظيف بالجبيل
    شركة عزل خزانات بالدمام
    شركة السفير المثالي للتنظيف بالدمام

  14. If you want to sell your old home furniture to buy new furniture you need to شركة شراء أثاث بالدمام

  15. It is great to have visited your website. Thanks for sharing useful information. And also visit my website about health. God willing it will be useful too

    Obat Sakit Dada
    Obat Tumor Jinak diatas Bola Mata
    Penyebab Benjolan dileher
    Obat Penghilang Nyeri Lutut
    Obat Penghilang Nyeri Pada Payudara
    Pengobatan penyakit Meningioma

  16. These dealers generally utilize charge card preparing, influencing a vendor to loan program an extraordinary subsidizing open door for them. Cash Advances corona

  17. Take every chance you get in life, because some things only happen once
    Cara Mengobati Nyeri Ulu Hati Seperti Ditusuk Tusuk

  18. Ayung Farma: Kami Jual Obat Aborsi Semarang Hub : 081348202800

    Cytotec Di Kaitkan Dengan Obat Aborsi Tuntas | Obat Penggugur Kandungan | Obat Pelancar Haid. Dengan harga yang bisa anda pilih sesuai usia kandungan anda. Obat Aborsi ini yang kami jual ampuh dan aman untuk menunda kehamilan atau proses pengguguran janin dalam usia kandungan 1 sampai 7bulan.

    obat aborsi semarang
    jual obat aborsi semarang
    obat aborsi janin semarang
    alamat aborsi semarang
    tempat aborsi semarang
    toko obat aborsi semarang
    penjual obat aborsi semarang
    cytotec asli semarang
    obat penggugur kandungan semarang
    penggugur janin di semarang
    obat aborsi tuntas di semarang
    klinik obat aborsi semarang
    obat peluntur janin semarang
    obat telat bulan semarang

  19. هل تبحث عن شركة متخصصة فى خدمات التنظيف بالطائف بافضل المعدات والسوائل وثقة تمة فى العمل ودقة فى النتائج كل هذه المميزت توفرها شركة الخليج الشركة الافضل والامثل فى الخدمات المنزلية بالطائف وبما اننا الشركة الافضل والامثل بدون منافس سوف نسعى لتوفر افضل الخدمات باقل تكلفة وبقدر كبير من الاهتمام والدقة عزيزى اينما كنت فى اى منطقة ا وحى تابع لمدينة الطائف اتصل بنا وسوف نصلك فى الحال شركة الخليج للخدمات المنزلية شركة تنظيف منازل بالطائف
    شركة تنظيف فلل بالطائف
    شركة تنظيف خزانات بالطائف
    شركة تسليك مجارى بالطائف
    شركة رش مبيدات بالطائف
    شركة مكافحة نمل ابيض بالطائف
    شركة مكافحة حشرات بالطائف
    شركة عزل اسطح بالطائف
    شركة عزل خزانات بالطائف

  20. It is a time consuming process to locate a legitimate, high-quality designer Michael Kors Handbags On Sale at a decent price. One brand name that is sought after is the Michael Kors Bags On Sale. Anywhere you see high demand you will find people out to make a quick buck.

  21. It is a time consuming process to locate a legitimate, high-quality designer Michael Kors Handbags On Sale at a decent price. One brand name that is sought after is the Michael Kors Bags On Sale. Anywhere you see high demand you will find people out to make a quick buck.

  22. There are those who want to collect vintage items like Michael Kors Factory Outlet with genuine and high quality leathers from Michael Kors. To be able to grab a quality Michael Kors Bags Outlet item of your choice, make sure to be very careful in selecting what to buy, how to buy and where to buy the Michael Kors Outlet Online.

  23. There are those who want to collect vintage items like Michael Kors Factory Outlet with genuine and high quality leathers from Michael Kors. To be able to grab a quality Michael Kors Bags Outlet item of your choice, make sure to be very careful in selecting what to buy, how to buy and where to buy the Michael Kors Outlet Online.

  24. Designer Exposure es un buen lugar para comprar su Bolsos Michael Kors original.
    The Woven Tote es también una selección impresionante en el Bolsos Michael Kors Baratos.
    Bolso de alta calidad que debe contemplar absolutamente un Bolsos Michael Kors Outlet.
    Du kommer att upptäcka en handfull detaljer som du kan förvänta dig att komma över på en vanlig Michael Kors Rea.
    Du kan hitta ett antal platser som ger Väska Michael Kors.
    Sortimentet är fantastiskt för alla som letar efter en MK Väska.
    Håll dina ögon öppna för den här säsongens val som kommer att presenteras under bara några månader och det kommer utan tvekan att bli spektakulärt.

  25. Good job in presenting the correct content with the clear explanation. The content looks real with valid information. Good Work

    DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

    Good to learn about DevOps at this time.

    devops training in chennai | devops training in chennai with placement | devops training in chennai omr | devops training in velachery | devops training in chennai tambaram | devops institutes in chennai | devops certification in chennai


  26. Such a wonderful article on AWS. I think its the best information on AWS on internet today. Its always helpful when you are searching information on such an important topic like AWS and you found such a wonderful article on AWS with full information.Requesting you to keep posting such a wonderful article on other topics too.
    Thanks and regards,
    AWS training in chennai
    aws course in chennai what is the qualification
    aws authorized training partner in chennai
    aws certification exam centers in chennai
    aws course fees details
    aws training in Omr

  27. Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
    artificial intelligence and machine learning course in chennai
    machine learning with python course in Chennai
    machine learning training in velachery
    Android training in chennai
    PMP training in chennai

  28. Thank you for sharing your article. Great efforts put it to find the list of articles which is very useful to know, Definitely will share the same to other forums.

    best openstack training in chennai | openstack course fees in chennai | openstack certification in chennai | openstack training in chennai velachery

  29. I know this is not fair i know this has happened
    Do you want to say I can't your tears no longer want to drip

    Obat Cantengan
    Cara Meningkatkan Nafsu Makan
    Cara Mengatasi Sakit Perut Bagian Atas

  30. Very interesting article, thank you for sharing. I also want to share the following health articles, God willing, useful. Thank you :)

    Obat Tradisional Turun Berok (Hernia)
    Perbedaan Gastritis dan Maag
    Obat Chikungunya Alami dan Ampuh

  31. Hi Bro,

    Nice article. thanks for your effort. I have a question. How to export the process in the article html & htm format desktop. I want to export instead of sending mail.


  32. atau malah sebaliknya, lawan menjadi semakin percaya diri dengan kombinasi kartu yang dimilikinya dan memutuskan untuk melipatgandakan taruhan.
    bandar ceme terbaik
    paito warna terlengkap
    forum prediksi

  33. Both things are possible if you carry Michael Kors Handbags Wholesale. If you are a woman who goes for innovative designs, a designer Michael Kors Bags On Sale is perfect for you. Offering a huge selection of chic purses, handbags, shoes and accessories, Michael Kors Outlet Online Store celebrates womanhood in an entirely unique way. Michael Kors Factory Outlet Online Store At Wholesale Price are one of the most sought-after handbags worldwide. We all agree that diamonds are a woman's best friend; however Official Coach Factory Outlet Online are absolutely next in line. To Coach Outlet Sale aficionados, don't fret because we have great news: a discount Official Coach Outlet Online isn't hard to find. If you are a smart shopper looking for a good buy and great deals on your next handbag purchase, you can go to Official Coach Outlet Online.

    Friendly Links: Toms Shoes Womens | Toms Clearance