MVP - Most Valuable Professional

Just can't get enough of IT

This blog is about mostly anything in IT. But the primary focuses are Microsoft technologies like Exchange Server, Microsoft 365, Microsoft Teams, and Cloud Security.
Thomas Stensitzki | MVP
Thomas Stensitzki | MVP

MVP LogoThomas Stensitzki is a leading technology consultant focusing on the Microsoft messaging and collaboration technologies and the owner of Granikos GmbH & Co. KG.

He is an MVP for Office Apps & Services since 2018.

Thomas is an MCT Regional Lead for Germany and delivers Microsoft Learning training courses for Office 365, Microsoft Teams, and Exchange Server.

He holds Master certifications as Microsoft Certified Solutions Master Messaging and as Microsoft Certified Master for Exchange Server 2010. These certifications make him a subject matter expert for any messaging topic related to Microsoft Exchange, Exchange Online, Microsoft 365, and hybrid configurations.

Follow Thomas: LinkedIn, Twitter

His sessions:

MVP Blog:
Personal blog:
Personal website:
Thomas' Tech Talk:

Contact Thomas at


Troubleshooting Outlook connectivity issues with Office 365 is tricky. Administrators can use two valuable tools provided by Microsoft to identify and even fix client related connectivity issues.

1. Outlook Account Test Page

Start with the Outlook account problems test page in the Office 365 portal. You need to log on as the Office 365 user having issues.

SARA Server

The site tests for the following:

  • You cannot create an Outlook profile or you are asked for your password repeatedly when creating one.
  • You cannot connect to your mailbox or receive an error that a mailbox cannot be found.
  • You are getting invalid license errors or messages that Office cannot verify the license.

If no issues are identified after you've logged on to Office 365, move to the next step.

2. Support and Recovery Assistant

The Microsoft Support and Recovery Assistant (SARA) for Office 365 is click to run tool that is installed and executed locally.

Support and Recovery Assistant (SARA)

These two tools fix most of the Outlook connectivity issues you are facing as an Office 365 administrator.



Enjoy Office 365

Read More »

This is a wrap-up of an older post that had originally been published on my former website.

Even though that this post focusses on Exchange 2010 transport agents, you will get an understand on what is required to create an Exchange 2013/2016 aka Version 15 transport agent.

Visual Studio Project

Writing your own transport agent for Exchange 2010 is not really complicated. With a Visual Studio C# Class project you are ready to go.

The follow picture shows the Visual Studio Solution as it has been used for the Message Modifier Solution.

Visual Studio Solution

Besides the C# class the solution contains the following Powershell script to simplify development and deployment:

  • Add-TransportAgent.ps1
    Installs the transport agent on the productive Exchange Server
  • Remove-TransportAgent.ps1
    Uninstalls the transport agent on the productive Exchange Server
    See Technet Gallery
  • Build-DeploymentPackage.ps1
    Copy all required DLLs, Powershell scripts and the deployment configuration file to a dedicated folder
  • install.ps1
    Installs the transport agent on the development Exchange Server
  • uninstall.ps1
    Uninstalls the transport agent on the development Exchange Server

The transport agent intercepts a message from a given sender address and performs the following actions:

  • If the message has attachments with file names starting with "WORKBOOK_" the attachments are renamed to the following format:

  • The subject is rewritten from the format

    [dd.MM.yyyy] [SUBJECT TEXT]
    [yyyyMMdd] [SUBJECT TEXT]



Code Sample

// AttachmentModify  
// ----------------------------------------------------------  
// Example for intercepting email messages in an Exchange 2010 transport queue  
// The example intercepts messages sent from a configurable email address(es)  
// and checks the mail message for attachments have filename in to format  
//      WORKBOOK_{GUID}  
// Changing the filename of the attachments makes it easier for the information worker  
// to identify the reports in the emails and in the file system as well.  
// Copyright (c) Thomas Stensitzki
// ----------------------------------------------------------  
using System;  
using System.Collections.Generic;  
using System.Diagnostics;  
using System.Globalization;  
using System.IO;  
using System.Reflection;  
using System.Text;  
using System.Text.RegularExpressions;  
using System.Threading;  
using System.Xml;  
// the lovely Exchange   
using Microsoft.Exchange.Data.Transport;  
using Microsoft.Exchange.Data.Transport.Smtp;  
using Microsoft.Exchange.Data.Transport.Email;  
using Microsoft.Exchange.Data.Transport.Routing;  
namespace SFTools.Messaging.AttachmentModify  
    #region Message Modifier Factory  
    /// <summary>  
    /// Message Modifier Factory  
    /// </summary>  
    public class MessageModifierFactory : RoutingAgentFactory  
        /// <summary>  
        /// Instance of our transport agent configuration  
        /// This is for a later implementation  
        /// </summary>  
        private MessageModifierConfig messageModifierConfig = new MessageModifierConfig();  
        /// <summary>  
        /// Returns an instance of the agent  
        /// </summary>  
        /// <param name="server">The SMTP Server</param>  
        /// <returns>The Transport Agent</returns>  
        public override RoutingAgent CreateAgent(SmtpServer server)  
            return new MessageModifier(messageModifierConfig);  
    #region Message Modifier Routing Agent  
    /// <summary>  
    /// The Message Modifier Routing Agent for modifying an email message  
    /// </summary>  
    public class MessageModifier : RoutingAgent  
        // The agent uses the fileLock object to synchronize access to the log file  
        private object fileLock = new object();  
        /// <summary>  
        /// The current MailItem the transport agent is handling  
        /// </summary>  
        private MailItem mailItem;  
        /// <summary>  
        /// This context to allow Exchange to continue processing a message  
        /// </summary>  
        private AgentAsyncContext agentAsyncContext;  
        /// <summary>  
        /// Transport agent configuration  
        /// </summary>  
        private MessageModifierConfig messageModifierConfig;  
        /// <summary>  
        /// Constructor for the MessageModifier class  
        /// </summary>  
        /// <param name="messageModifierConfig">Transport Agent configuration</param>  
        public MessageModifier(MessageModifierConfig messageModifierConfig)  
            // Set configuration  
            this.messageModifierConfig = messageModifierConfig;  
            // Register an OnRoutedMessage event handler  
            this.OnRoutedMessage += OnRoutedMessageHandler;  
        /// <summary>  
        /// Event handler for OnRoutedMessage event  
        /// </summary>  
        /// <param name="source">Routed Message Event Source</param>  
        /// <param name="args">Queued Message Event Arguments</param>  
        void OnRoutedMessageHandler(RoutedMessageEventSource source, QueuedMessageEventArgs args)  
            lock (fileLock) {  
                try {  
                    this.mailItem = args.MailItem;  
                    this.agentAsyncContext = this.GetAgentAsyncContext();  
                    // Get the folder for accessing the config file  
                    string dllDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);  
                    // Fetch the from address from the current mail item  
                    RoutingAddress fromAddress = this.mailItem.FromAddress;  
                    Boolean boWorkbookFound = false;    // We just want to modifiy subjects when we modified an attachement first  
                    #region External Receive Connector Example  
                    // CHeck first, if the mail item does have a ReceiveConnectorName property first to prevent ugly things to happen  
                    if (mailItem.Properties.ContainsKey("Microsoft.Exchange.Transport.ReceiveConnectorName")) {  
                        // This is just an example, if you want to do something with a mail item which has been received via a named external receive connector  
                        if (mailItem.Properties["Microsoft.Exchange.Transport.ReceiveConnectorName"].ToString().ToLower() == "externalreceiveconnectorname")  
                            // do something fancy with the email  
                    RoutingAddress catchAddress;  
                    // Check, if we have any email addresses configured to look for  
                    if (this.messageModifierConfig.AddressMap.Count > 0) {  
                        // Now lets check, if the sender address can be found in the dictionary  
                        if (this.messageModifierConfig.AddressMap.TryGetValue(fromAddress.ToString().ToLower(), out catchAddress)) {  
                            // Sender address found, now check if we have attachments to handle  
                            if (this.mailItem.Message.Attachments.Count != 0) {  
                                // Get all attachments  
                                AttachmentCollection attachments = this.mailItem.Message.Attachments;  
                                // Modify each attachment  
                                for (int count = 0; count < this.mailItem.Message.Attachments.Count; count++) {  
                                    // Get attachment  
                                    Attachment attachment = this.mailItem.Message.Attachments[count];  
                                    // We will only transform attachments which start with "WORKBOOK_"  
                                    if (attachment.FileName.StartsWith("WORKBOOK_")) {  
                                        // Create a new filename for the attachment  
                                        // [MODIFIED SUBJECT]-[NUMBER].[FILEEXTENSION]  
                                        String newFileName = MakeValidFileName(string.Format("{0}-{1}{2}", ModifiySubject(this.mailItem.Message.Subject.Trim()), count + 1, Path.GetExtension(attachment.FileName)));  
                                        // Change the filename of the attachment  
                                        this.mailItem.Message.Attachments[count].FileName = newFileName;  
                                        // Yes we have changed the attachment. Therefore we want to change the subject as well.  
                                        boWorkbookFound = true;  
                                // Have changed any attachments?  
                                if (boWorkbookFound) {  
                                    // Then let's change the subject as well  
                                    this.mailItem.Message.Subject = ModifiySubject(this.mailItem.Message.Subject);  
                catch (System.IO.IOException ex) {  
                    // oops  
                finally {  
                    // We are done  
            // Return to pipeline  
        /// <summary>  
        /// Build a new subject, if the first 10 chars of the original subject are a valid date.  
        /// We muste transform the de-DE format dd.MM.yyyy to yyyyMMdd for better sortability in the email client.  
        /// </summary>  
        /// <param name="MessageSubject">The original subject string</param>  
        /// <returns>The modified subject string, if modification was possible</returns>  
        private static string ModifiySubject(string MessageSubject)  
            string newSubject = String.Empty;  
            if (MessageSubject.Length >= 10) {  
                string dateCheck = MessageSubject.Substring(0, 10);  
                DateTime dt = new DateTime();  
                try {  
                    // Check if we can parse the datetime  
                    if (DateTime.TryParse(dateCheck, out dt)) {  
                        // lets fetch the subject starting at the 10th character  
                        string subjectRight = MessageSubject.Substring(10).Trim();  
                        // build a new subject  
                        newSubject = string.Format("{0:yyyyMMdd} {1}", dt, subjectRight);  
                finally {  
                    // do nothing  
            return newSubject;  
        /// <summary>  
        /// Replace invalid filename chars with an underscore  
        /// </summary>  
        /// <param name="name">The filename to be checked</param>  
        /// <returns>The sanitized filename</returns>  
        private static string MakeValidFileName(string name)  
            string invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));  
            string invalidRegExStr = string.Format(@"[{0}]+", invalidChars);  
            return Regex.Replace(name, invalidRegExStr, "_");  
    #region Message Modifier Configuration  
    /// <summary>  
    /// Message Modifier Configuration class  
    /// </summary>  
    public class MessageModifierConfig  
        /// <summary>  
        ///  The name of the configuration file.  
        /// </summary>  
        private static readonly string configFileName = "SFTools.MessageModify.Config.xml";  
        /// <summary>  
        /// Point out the directory with the configuration file (= assembly location)  
        /// </summary>  
        private string configDirectory;  
        /// <summary>  
        /// The filesystem watcher to monitor configuration file updates.  
        /// </summary>  
        private FileSystemWatcher configFileWatcher;  
        /// <summary>  
        /// The from address  
        /// </summary>  
        private Dictionary<string, RoutingAddress> addressMap;  
        /// <summary>  
        /// Whether reloading is ongoing  
        /// </summary>  
        private int reLoading = 0;  
        /// <summary>  
        /// The mapping between domain to catchall address.  
        /// </summary>  
        public Dictionary<string, RoutingAddress> AddressMap  
            get { return this.addressMap; }  
        /// <summary>  
        /// Constructor  
        /// </summary>  
        public MessageModifierConfig()  
            // Setup a file system watcher to monitor the configuration file  
            this.configDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);  
            this.configFileWatcher = new FileSystemWatcher(this.configDirectory);  
            this.configFileWatcher.NotifyFilter = NotifyFilters.LastWrite;  
            this.configFileWatcher.Filter = configFileName;  
            this.configFileWatcher.Changed += new FileSystemEventHandler(this.OnChanged);  
            // Create an initially empty map  
            this.addressMap = new Dictionary<string, RoutingAddress>();  
            // Load the configuration  
            // Now start monitoring  
            this.configFileWatcher.EnableRaisingEvents = true;  
        /// <summary>  
        /// Configuration changed handler.  
        /// </summary>  
        /// <param name="source">Event source.</param>  
        /// <param name="e">Event arguments.</param>  
        private void OnChanged(object source, FileSystemEventArgs e)  
            // Ignore if load ongoing  
            if (Interlocked.CompareExchange(ref this.reLoading, 1, 0) != 0) {  
                Trace.WriteLine("load ongoing: ignore");  
            // (Re) Load the configuration  
            // Reset the reload indicator  
            this.reLoading = 0;  
        /// <summary>  
        /// Load the configuration file. If any errors occur, does nothing.  
        /// </summary>  
        private void Load()  
            // Load the configuration  
            XmlDocument doc = new XmlDocument();  
            bool docLoaded = false;  
            string fileName = Path.Combine(this.configDirectory, MessageModifierConfig.configFileName);  
            try {  
                docLoaded = true;  
            catch (FileNotFoundException) {  
                Trace.WriteLine("Configuration file not found: {0}", fileName);  
            catch (XmlException e) {  
                Trace.WriteLine("XML error: {0}", e.Message);  
            catch (IOException e) {  
                Trace.WriteLine("IO error: {0}", e.Message);  
            // If a failure occured, ignore and simply return  
            if (!docLoaded || doc.FirstChild == null) {  
                Trace.WriteLine("Configuration error: either no file or an XML error");  
            // Create a dictionary to hold the mappings  
            Dictionary<string, RoutingAddress> map = new Dictionary<string, RoutingAddress>(100);  
            // Track whether there are invalid entries  
            bool invalidEntries = false;  
            // Validate all entries and load into a dictionary  
            foreach (XmlNode node in doc.FirstChild.ChildNodes) {  
                if (string.Compare(node.Name, "domain", true, CultureInfo.InvariantCulture) != 0) {  
                XmlAttribute domain = node.Attributes["name"];  
                XmlAttribute address = node.Attributes["address"];  
                // Validate the data  
                if (domain == null || address == null) {  
                    invalidEntries = true;  
                    Trace.WriteLine("Reject configuration due to an incomplete entry. (Either or both domain and address missing.)");  
                if (!RoutingAddress.IsValidAddress(address.Value)) {  
                    invalidEntries = true;  
                    Trace.WriteLine(String.Format("Reject configuration due to an invalid address ({0}).", address));  
                // Add the new entry  
                string lowerDomain = domain.Value.ToLower();  
                map[lowerDomain] = new RoutingAddress(address.Value);  
                Trace.WriteLine(String.Format("Added entry ({0} -> {1})", lowerDomain, address.Value));  
            // If there are no invalid entries, swap in the map  
            if (!invalidEntries) {  
                Interlocked.Exchange<Dictionary<string, RoutingAddress>>(ref this.addressMap, map);  
                Trace.WriteLine("Accepted configuration");  



Read More »

There are three different ways to configure new Exchange user mailboxes after these have been created.

  • The classic manual administrator approach (keeps your job safe, but is it fun?)
  • The workflow based approach using some kind of IDM workflow solution (keeps the IDM consultant's job safe)
  • The scripting agent approach by extending the Exchange cmdlets (keeps your job safe, is fun, keeps you in control and get's you more free time)

The Exchange cmdlet extension is controlled by a scripting agent configuration file and a organizational setting to enable/disable the scripting agent.


A scripting agent configuration file sample (ScriptingAgentConfig.xml.sample) is located in

  • $exinstall\Bin\CmdletExtensionAgents

The sample needs to be renamed to ScriptingAgentConfig.xml, to be picked up the PowerShell engine.

As always, a slight reminder: Test any modification in a test environment first, before you use the extension in a production environment.

After succesfull testing and deployment, you need to enable the scripting agent using

Enable-CmdletExtensionAgent "Scripting Agent"


Even thought that you can extend mostly any Exchange cmdlet, this example covers the extension of the New-Mailbox and Enable-Mailbox cmdlets in a multi domain and multi AD site environment.

This extension disables the following CAS mailbox settings, after a new mailbox has been created:

  • ActiveSync
  • IMAP4
  • POP3
  • MAPI over HTTP

What does the example do?

  • Extension is named MailboxProvisioning and handles the cmdlets New-Mailbox and Enable-Mailbox
  • Is called on trigger OnComplete
    • The extension code is called after the original cmdlet has finished
  • Code is executed, if the original cmdlet was successfully finished
  • Code is executed, if the mailbox created is not an archive
  • A slight delay of 10 seconds ensures that domain controller activities have been finished
    • Can be adjusted or even removed, depending on your environment
  • Try to fetch at least on of three user parameters to identify the user mailbox
    • Checking for Identity, Name, Alias
  • Fetch a list of all domain controllers in the current AD site where the Exchange server is located
  • Iterate through the list of domain controllers and try to fetch the new CAS mailbox
    • If fetched, remember the domain controller's FQDN
  • Change the CAS mailbox settings as needed and use the remembered domain controller as DC to write to


<?xml version="1.0" encoding="utf-8" ?>
  <Configuration version="1.0">
	<Feature Name="MailboxProvisioning" Cmdlets="New-Mailbox,Enable-Mailbox">
		<ApiCall Name="OnComplete">
			If ($succeeded) {
				if (!($provisioningHandler.UserSpecifiedParameters.Archive -eq $true)) {
					# delay execution for 10 seconds, adjust as needed
					Start-Sleep -s 10
					# validate parameters to use a not null parameter
					if ($provisioningHandler.UserSpecifiedParameters["Identity"] -ne $null) {
						$user = $provisioningHandler.UserSpecifiedParameters["Identity"].ToString()
					elseif ($provisioningHandler.UserSpecifiedParameters["Name"] -ne $null) {
						$user = $provisioningHandler.UserSpecifiedParameters["Name"].ToString()
					else {
						$user = $provisioningHandler.UserSpecifiedParameters["Alias"].ToString()
					# view entire forest in a multi domain environment
					Set-AdServerSettings -ViewEntireForest:$true
					# fetch domain controllers in AD site}
					$server = Get-ExchangeServer $env:computername
					$DCs = Get-DomainController | ?{$_.adsite -eq $}
					$CasMailbox = $null
					foreach($d in $DCs) {
						while($CasMailbox -eq $null) {
							# find a valid domain controller having the updated user object
							$CasMailbox = Get-CASMailbox $user -DomainController $d.dnshostname -ErrorAction SilentlyContinue
							# fetch DCs FQDN
							$WriteDC = $d.DnsHostName
					try {
						# set CAS features as needed
						Set-CasMailbox $user -ActiveSyncEnabled:$false -ImapEnabled:$false -PopEnabled:$false -MapiHttpEnabled:$false -DomainController $WriteDC -ErrorAction SilentlyContinue
					catch {}


After adding the PowerShell code to the ScriptingAgentConfig.xml file, the file needs to be distributed across all Exchange servers. For distribution of the scripting agent configuration file I personally recommend Paul Cunningham's PowerShell script.

Be aware of the fact, that the scripting agent Xml is being validated using a strict schema validation. The scripting agent Xml is case sensitive, as noted here.


Read More »
Last updated: 2018-01-16

Exchange Server 2013Exchange Server 2016Description

The community script Update-CASMailbox simplifies the process for enabling or disabling protocols for Exchange mailbox access. Active Directory security groups are used to enable or disable a protocol for the group members.


Your Active Directory contains a security group named Exchange_POP_enabled which contains all mailbox users requiring POP3 access to be enabled.

You can use the following command to have POP3 enabled for all members of the given security group.

.\Update-CAS-Mailbox.ps1 -POP -FeatureEnabled $true -GroupName Exchange_POP_enabled

The script does not disable the POP3 for all non-members, as this might not be required as all new mailboxes have POP3 disabled anyway. If there is such a requirement, just let me know.

The following protocols are currently supported:

  • POP
  • IMAP
  • Outlook on the Web (OWA)
  • ActiveSync




You need assistance with your Exchange Server setup? You have questions about your Exchange Server infrastructure and going hybrid with Office 365? You are interested in what Exchange Server 2016 has to offer for your environment?

Read More »
On April 22, 2016
0 Comment

The PowerShell script Get-Diskspace.ps1 uses a pretty basic inline CSS approach to generate a more nicely html email from a PowerShell output.

You can use the following description for your own PowerShell script.

First a new html block is configured and the inline CSS is embedded into the head tag.

# Some CSS to get a pretty report
# Variable containing the inline CSS and the full html head tag
$head = @'
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "">
<style type=”text/css”>
body {
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
h2{ clear: both; font-size: 100%;color:#354B5E; }
    clear: both;
    font-size: 75%;
    margin-left: 20px;
    margin-top: 30px;
    border-collapse: collapse;
    border: none;
    font: 10pt Verdana, Geneva, Arial, Helvetica, sans-serif;
    color: black;
    margin-bottom: 10px;
table td{
    font-size: 12px;
    padding-left: 0px;
    padding-right: 20px;
    text-align: left;
table th {
    font-size: 12px;
    font-weight: bold;
    padding-left: 0px;
    padding-right: 20px;
    text-align: left;

The recurring data content is added to a global varibale using the -Fragment attribute. This ensures that no full html document data is being created.

$global:Html += $wmi | ConvertTo-Html -Fragment -PreContent "<h2>Server $($ServerName)</h2>"

Before sending the html result the full body html is generated by combinding the html fragments and the manually defined html head.

[string]$Body = ConvertTo-Html -Body $global:Html -Title "Status" -Head $head

Send-Mail -From $MailFrom -To $MailTo -SmtpServer $MailServer -MessageBody $Body -Subject $ReportTitle  


Read More »