Unable to delete items in modern public folders : “Some Items cannot be deleted. They were either moved or already deleted, or access was denied”

Recently we had reports from a subset of users that they received the following error when they tried to deleted items from a specific set of public folders using their Outlook client: “Some Items cannot be deleted. They were either moved or already deleted, or access was denied”

A quick google search revealed that this happens to a mailbox whenever it goes over its RecoverableItemsQuota. Seeing that this was an Exchange 2013 environment, and starting in Exchange 2013 public folders are now stored in mailboxes, I assumed the same symptom was occurring. Sure enough the public folder mailbox these folders resided in was over its deleted item limit.

Get-Mailbox pubfoldermbx01 -PublicFolder | Select Name, *recoverable*
Name            RecoverableItemsQuota         RecoverableItemsWarningQuota
----            ---------------------         ----------------------------
PubFolderMbx02  60 GB (64,424,509,440 bytes)  40 GB (42,949,672,960 bytes)
 
Get-Mailbox pubfoldermbx0q -PublicFolder | Get-MailboxStatistics | Select DisplayName, TotalDeletedItemSize
DisplayName     TotalDeletedItemSize
-----------     --------------------
PubFolderMbx01  60 GB (64,424,509,440 bytes)

Another folder in the same public folder mailbox was taking up most the deleted item space of the mailbox. You can find this out by running the following

$PFStats = Get-PublicFolder -ResidentFolders -Mailbox pubfoldermbx01 -Recurse | Get-PublicFolderStatistics
 
$PFStats | Select Name, FOlderPath, TotalDeletedItemSize | Sort TotalDeletedItemSize -Descending | select -First 3
Name              FolderPath           TotalDeletedItemSize
----              ----------           --------------------
Offending Folder  {Offending Folder}   59.10 GB (63,458,141,798 bytes)
CLEAN             {CLEAN}	       3.517 GB (3,776,367,512 bytes)
Inbox             {Inbox}	       1.715 GB (1,841,476,727 bytes)

At this point we temporarily set the RecoverableItemsQuota on this public folder mailbox to unlimited reached out to the owners of the offending public folder.

Get-Mailbox -PublicFolder pubfoldermbx01 | Set-Mailbox -UseDatabaseRetentionDefaults $FALSE -PublicFolder
 
Get-Mailbox -PublicFolder pubfoldermbx01 | Set-Mailbox -RetainDeletedItemsFor $NULL –PublicFolder

We learned they were using the folder as a dumping group for alert messages from a system in their development environment, which was generating close to 10,000 messages a day. After explaining the situation and its impact on other users, the public folder owners agreed to a shorter item age and deleted item retention period.

Set-PublicFolder "\Offending Folder" -RetainDeletedItemsFor 0 -AgeLimit 5

We could have also moved the public folder to its own mailbox, but we decided that it would be best to try to limit how long the data was being held instead of continuing to accommodate a large volume of non-critical data.  After about 48 hours the new retention policy kicked in. This is due to the Managed folder assistant needing to first stamp the items with the new retention settings during the first past and then to act on the new stamp after the second pass. This process usually happens every 24 hours in Exchange 2013+. You can manually kick it off using Start-ManagedFolderAssistant like so

Start-ManagedFolderAssistant -Identity pubfoldermbx01
Posted in Exchange, Exchange 2013, Public Folders | Leave a comment

Using script blocks within doubled quoted strings in PowerShell

While working on a script to convert an XML export of a new chat application to EML files for ingestion into my company’s compliance system (A task I’ve been doing a lot of over the past year or so), I came across an interesting use of variable usage in double quoted strings. One I was surprised I didn’t think of earlier.
Part of my script entailed providing options for grabbing various date ranges of the XML chat export from the provided REST API. I decided on the following options:

  • Full Export
  • This Date Forward
  • This Date Only

I normally use write-verbose statements partially as comment based help and a light version of logging for scripts like this. So when a non-full export was specified I wanted a write verbose statement like

Write-Verbose "Building REST URL for a $ExportType export using $ExportStartDate"

While a full export would be

Write-Verbose "Building REST URL for a $ExportType”

So I originally started with the following code

if ($ExportType -ne “Full”) {
Write-Verbose "Building REST URL for a $ExportType export using $ExportStartDate"
}
Else {
Write-Verbose "Building REST URL for a $ExportType export"
}

But then it dawned on me, I’ve done some expressions in double quoted strings before. A simple example would be

Write-host “Yesterday was $((Get-date -Hour 00 -Minute 00 -Second 00).adddays(-1).tostring())"

Could I do something a little more complex? Turns out I can! The following worked and could fit on one line

Write-Verbose "Building REST URL for a $ExportType export $(if($ExportType -ne “Full”) {"using $ExportStartDate"})"

Thinking about it some more. I wondered if I had a more complex statement as a script block. Could I pass that as well? Turns out I can!

[ScriptBlock]$CalculatedValue = {if($ExportType -ne “Full”) {"using $ExportStartDate"}}
Write-host "Building REST URL for a $ExportType export $(& $CaculdateValue)"
Write-host "Building REST URL for a $ExportType export $(Invoke-Command $CaculdateValue)"

Using either the call operator (&) or Invoke-Command I can execute a script block in a double quoted string. A fun trick I hope to use in the future to tighten up some code.

Posted in PowerShell | Leave a comment

Creating an array of arrays in powershell

Recently I had a need to convert a series of messages from one of my company’s Slack instances into EML files so they could be ingested into our compliance system. In the process of parsing the export file via PowerShell, I had the need to group individual messages by conversations for further processing. This meant I needed an array of message threads, and each thread could be a single or multiple messages (another array). But when I was doing the standard method of adding an object to an array

$MessageTable += $Thread

it was instead adding the individual array members of $Tread to object to $MessageTable instead of adding it as a single object. So for threads with multiple messages I was joining the arrays instead. In order to do this I had to do the following:

$MessageTable += ,$Thread

The big differences was the comma ( , ). This allowed each array to be added as an entire object instead of being joined. As a better explanation, here is an example through pseudo PowerShell code

Create an array to hold all the objects called $MessageTable

$MessageTable = @()

Do some work to create the following thread, which contains only one message object

$Thread =
 
type : message
user : john.mello@contso.com
text : FYI meeting tommorrow
ts : 10/10/2016 8:42:25 PM
MsgType : Direct Message
participants : Chad.Doe@contso.com

Now add it to the $MessageTable as an object

$MessageTable += ,$Thread

Do some more work to create a new thread, which contains 3 message objects

$Thread =
 
type : message
user : john.mello@contso.com
text : do you have tickets for next week? if not i was going to get them.
ts : 10/10/2016 10:40:12 AM
MsgType : Direct Message
participants : {jane.brown@contso.com}
 
type : message
user : john.mello@contso.com
text: have 2 meetings for the AM on the 18th, but afternoon is free
ts&: 10/10/2016 10:40:36 AM
MsgType : Direct Message
participants : {jane.brown@contso.com}
 
type : message
user: jane.brown@contso.com
text: No tickets yet.
ts : 10/10/2016 11:04:56 AM
MsgType: Direct Message
participants : {john.mello@contso.com}

Now add it to the $MessageTable as an object  as well

$MessageTable += ,$Thread

Now when I check the count of the $MessageTable object I see that it only has 2 total objects

$MessageTable.count
2

I can also see that each item is references as the whole object

$MessageTable[0]
 
type : message
user : john.mello@contso.com
text : FYI meeting tommorrow
ts : 10/10/2016 8:42:25 PM
MsgType : Direct Message
participants : Chad.Doe@contso.com
 
$MessageTable[1]
 
type : message
user : john.mello@contso.com
text : do you have tickets for next week? if not i was going to get them.
ts : 10/10/2016 10:40:12 AM
MsgType : Direct Message
participants : {jane.brown@contso.com}
 
type : message
user: john.mello@contso.com
text: have 2 meetings for the AM on the 18th, but afternoon is free
ts : 10/10/2016 10:40:36 AM
MsgType : Direct Message
participants : {jane.brown@contso.com}
 
type : message
user : jane.brown@contso.com
text: No tickets yet.
ts& : 10/10/2016 11:04:56 AM
MsgType : Direct Message
participants : {john.mello@contso.com}

Now if I did it the normal way ($MessageTable += $Thread), each message would have been joined to the array

$MessageTable.count
4
 
$MessageTable[0]
 
type : message
user : john.mello@contso.com
text : FYI meeting tommorrow
ts : 10/10/2016 8:42:25 PM
MsgType : Direct Message
participants : Chad.Doe@contso.com
 
$MessageTable[1]
 
type : message
user : john.mello@contso.com
text : do you have tickets for next week? if not i was going to get them.
ts : 10/10/2016 10:40:12 AM
MsgType : Direct Message
participants : {jane.brown@contso.com}
 
$MessageTable[2]
 
type message
user : john.mello@contso.com
text: have 2 meetings for the AM on the 18th, but afternoon is free
ts: 10/10/2016 10:40:36 AM
MsgType: Direct Message
participants : {jane.brown@contso.com}
 
$MessageTable[3]
 
type : message
user : jane.brown@contso.com
text : No tickets yet.
ts : 10/10/2016 11:04:56 AM
MsgType : Direct Message
participants : {john.mello@contso.com}

Now I could have also used an Array List, which always adds the whole object as one entry in the array. An Array lists also has the following benefits which I frequently use

  • Has a remove() method with Array does not
  • More efficient when adding hundreds of members because the += method makes PowerShell create a new variable equal to the whole of the old one, add our new entry to the end, and then throws away the old variable

Here is how I would use it in the same situations

Create the array list

$MessageTable = New-Object System.Collections.ArrayList

Use the add method to add an object

$MessageTable.Add($Thread)
0
 
#MORE WORK
 
$MessageTable.Add($Thread)
1

Note that an Array list will always return the current addressable location of the object added to the console, in order to avoid that use your favorite out null method. Example

$MessageTable.Add($Thread) | Out-Null

Here is a fully fleshed out example using get-process

#Arrays
$Array1 = @()
$Array2 = @()
$ArrayList = New-Object System.Collections.ArrayList
 
#Data
$Process_W = Get-Process -Name W*
$Process_S = Get-Process -Name S*
 
#Joining Arrays example
$Array1 += $Process_W
$Array1 += $Process_S
$Array1.count
$Array1[1]
 
#Adding arrays to array example
$Array2 += ,$Process_W
$Array2 += ,$Process_S
$Array2.count
$Array2[1]
 
#Array list example
$ArrayList.add($Process_W)
$ArrayList.add($Process_S) | Out-Null
$ArrayList.count
$ArrayList[1]
Posted in PowerShell | Leave a comment

The various picture resolutions supported by Exchange 2013 mailboxes

In researching what picture resolutions are supported by Exchange (and Lync 2013/Skype for business) I came across this MS Technet article stating the the following 3 resolutions used in Lync:

  • 48 x 48 : Used if no higher resolution image is selected
  • 96 x 96 : Used in Outlook Web App and Outlook 2013
  • 648 x 648 : Used in Lync 2013 desktop client and Lync 2013 Web App

I also came across this MSDN article detailing an EWS URL you can use to retrieve the photo used in an Exchange 2013 mailbox : https://Exchange Server/ews/Exchange.asmx/s/GetUserPhoto?email=email address&size=size code
In working on a script to pull pictures from my company’s HR system and push them to user’s mailboxes, I noticed other resolutions were available as well. So I decided to try and figure out all the supported resolutions with this quick and dirty PoweShell script:

Foreach ($Num in 1..648) {
   Try {
      $URL = "http://contoso.com/EWS/Exchange.asmx/s/GetUserPhoto?email=John.Mello@contoso.com&size=HR$($Num)x$($Num)" Invoke-WebRequest -Uri $URL -UseDefaultCredentials -ErrorAction stop | Out-NUll
      $Num
   }
   Catch{ } 
}

In doing so I discovered that these were all the supported resolutions in Exchange 2013:

  • 48×48
  • 64×64
  • 96×96
  • 120×120
  • 240×240
  • 360×360
  • 432×432
  • 504×504
  • 648×648
Posted in EWS, Exchange 2013, Outlook | Leave a comment

Display Names on mail enabled public folders in Exchange 2013

Fun fact, you can have a different display for the same public folder if it’s mail enabled

[PS] Get-PublicFolder "\Market Data Services\MDS Bills" | Select Identity, Name | Ft -AutoSize
Identity                        Name
--------                        ----
\Market Data Services\MDS Bills MDS Bills
[PS] Get-MailPublicFolder "\Market Data Services\MDS Bills" | Select Identity, Alias, Displayname, name | FT -AutoSize
Identity                                                        Alias       DisplayName   Name
--------                                                        -----       -----------   ----
contso.com/Microsoft Exchange System Objects/OLD MDS Bills OLDMDSBILLS OLD MDS Bills OLD MDS Bills

This happens because the mail enabled object is an object that resides in AD in the Microsoft Exchange System Objects OU, while the standard folder is just a folder in the public folder mailboxes

Posted in Exchange, Exchange 2013 | Leave a comment

I took my Exchange 2013 environment down doing a CU11 prerequisite check

In preparing for my company’s Exchange 2013 CU8 to CU11 uprage a few weekends ago I decided during my lunch break to the run the CU11 installer through the prerequisite check on all our servers just to make sure nothing would get in the way of the install that weekend. This is something I used to do all the time in Exchange 2010 with Service packs and Roll ups. So I started the GUI setup on one of our multi role servers hosting a lagged database in our DR site first and the prerequisite check came up clean so I exited out of the installer at the section where you would normally hit “next” to install Exchange 2013. I then ran it on one of our production servers and it came up clean as well. Figuring I should be thorough, I ran the prerequisite check on the remaining production and DR servers. Within a few minutes we started getting multiple alarms for our Exchange email environment through out monitoring system. After 45 minutes of email routing and access down time I was able to piece together that the prerequisite check runs the following which puts the following 3 Exchange 2013 component states offline

Set-ServerComponentState $Target -Component Monitoring -Requester Functional -State Inactive
Set-ServerComponentState $Target -Component RecoveryActionsEnabled -Requester Functional -State Inactive
Set-ServerComponentState $Target -Component ServerWideOffline -Requester Functional -State InActive

Unfortunately the setup does not put them back online if you cancel it for any reason. Early in the trouble shooting process I realized that the components states were in an inactive state and I tried to bring them back online (like I normally do when patching). What I didn’t realize was that since the Requester was “Functional” and I was using “Maintenance” to try and bring them back online, it wasn’t taking. Only after I did so using “Functional” did it take.

After doing a post mortem on the issue at work we came across the following info online

This Exchange team blog post from 09/26/2013 that states the following

While an Exchange 2013 Server is updated with CU2, the setup- sets “Monitoring”, “RecoveryActionsEnabled” and “ServerWideOffline” to Inactive using the Requester “Functional” at the beginning, as can be seen in the “ExchangeSetup”-Logfile:

However, when the update exits prematurely because it encounters an unrecoverable error-condition, it does not restore the original state. Even when the Administrator restarts all stopped Exchange services or reboots the server, the Exchange components still remain in the Inactive state.

In order to recover from this situation, you must either find the root cause for the error and remove it so that the setup completes successfully, or manually set the ServerComponentStates back to Active with the Requester “Functional”.

This issue might be fixed in future CUs and SPs.

When I looked over my Exchange install log files I did not see any entries stating an abnormal end, but it appears that simply cancelling the setup after the prerequisite check is enough to cause this condition. I persoanlly wish this was actively stated in the setup process itself (e.g. “Putting this server in ServerWideOffline mode, do you want to continue?”)

This TechNet Blog from 10/21/2014 states the following about running a CU and when the server component states are set to inactive:

In Exchange 2013, we have also extended setup to perform some of the maintenance tasks prescribed here – specifically handling server health states to ensure that the server can be safely upgraded. When performing setup.exe /mode:upgrade to upgrade between Exchange 2013 CUs we now perform the following:

  • Set the monitoring state of the server to inactive.
  • Prevent automatic recovery actions from occurring on the server.
  • Set the ServerWideOffline component state to InActive

This essentially disables all health checking against the server, all automatic recovery actions as a result of that health checking, and prevents the server from performing transport and other client functions.

….

It should be noted that these steps are executed directly at the beginning of setup – even before pre-requisite analysis etc.

So all in all, I didn’t realize running the install up to the prerequisite check would cause so many issues. This is our first CU update since we deployed Exchange 2013 and I don’t recall running into this issue in 2010 when I deployed SPs or RUs. So hopefully this will help someone else out before they make the same mistake.

 

Posted in Exchange, Exchange 2013 | Leave a comment

Dealing with User Photos in Exchange 2010 and 2013

I recently update my teams internal documentation for how Photos are handled in Excahnge 2013 and figure it might be helpful to others, enjoy!

 

Outlook 2010 and Exchange 2010

Outlook 2010/Exchange 2010 pulls from the AD attribute thumbnailPhoto. This attribute can hold up to a 100K file but keep in mind this increases the size of the Active Directory database. The recommended size for Exchange 2010 and Outlook 2010 is a 10K file that is 96×96 pixels. These pictures are only displayed internally and are not accessible to anyone outside of the Exchange environment unless federation between other organizations has been put in place.

This attribute can be populated via the following methods:

  1. AD cmdlet
    1. $photo = [byte[]](Get-Content "C:\Photos\User.jpg" -Encoding byte)
    2. Set-ADUser USERNAME -Replace @{thumbnailPhoto=$photo}
  2. Exchange cmdlet
    1. Import-RecipientDataProperty -Identity USERNAME -Picture -FileData ([Byte[]]$(Get-Content -Path "C:\Photos\User.jpg" -Encoding Byte -ReadCount 0))
  3. 3rd party GUI tools  like AD Photo Edit

This attribute can be cleared via the following methods

  1. AD cmdlet
    1. Set-ADUser USERNAME -Clear Thumbnailphoto
  2. Exchange cmdlet
    1. Set-Mailbox USERNAME -RemovePicture
  3. 3rd party GUI tools like AD Photo Edit
  4. Active Directory Service Interfaces Editor (ADSI Edit)
  5. Active Directory Users and computers
    1. Go to user account -> Attribute Editor -> thumbnailPhoto -> Clear

By default users have the ability to change their own attribute, but can only do so via a 3rd party tool like AD Photo Edit or via the command line. End users can be denied the ability to change their own thumbnailPhoto attribute in AD by denying  SELF the “Write thumbnailPhoto” permission on that user’s AD object. This needs to be done on each individual account and cannot be done at an OU level. The reason being is that by default an User account is allowed to edit its own personal information and this explicit allow on a user object takes precedence over an inherited deny from the OU. Currently no “one stop” method to change this attribute from a user perspective exists in Exchange 2010

Once the thumbnailPhoto attribute has been updated, Outlook 2010 Clients in online mode (and Outlook Web Access) will be able to see the picture immediately. Outlook 2010 clients in cached mode will see the picture the next time the Exchange Offline Address Book is updated, which is every day at 5AM, 11AM, and 5PM by default. Note that the OAB does not contain the actual picture files but directs the Outlook client to pull them from Active Directory.

Outlook 2010 clients in cached mode will download the Offline Address Book once every 24 hours. This can be forced at any time in Outlook 2010 by going to the Send / Receive Tab -> Send/Receive Groups drop down -> Download Address Book… .

DownloadAddressBook

Then a window labeled Offline Address book – USER NAME will pop-up, make sure the following settings are set:

  • Check the box for Download changes since last Send/Receive
  • Radio button for Full Details selected
  • From the Choose address book drop down select \Global Address List

Then click the OK button. Depending on the traffic to and from the Exchange server this process can take up to 30 minutes.

AddresBook

Note that the option to Show User Photographs when available (under File -> Options -> Contacts) in Outlook 2010 does not clear out the users thumbnailPhoto attribute in AD, it only stops the Outlook 2010 client from displaying the photos stored in that attribute.

Updates to Exchange 2013

Exchange 2013 has the following enhancements in regards to photos:

  1. Exchange now stores a higher res version (up to 648×648 pixels) of a user photo directly in a user’s mailbox, and applications like Outlook, Lync, and SharePoint will pull the picture via EWS
    1. The only limit to setting photos is that is must be under 20MB.
    2. If a picture larger than 648×648 is upload and
      1. it’s a perfect square then Exchange will scale it down to 648×648
      2. It’s not a perfect square then Exchange will grab 648×648 pixel portion of the picture that resides in the center of the picture, with a slight bias (~15%) to the top half
        1. grid
      3. When the picture is uploaded to the mailbox a 48×48 pixel version is also stored in the thumbnailPhoto AD attribute of the user
        1. Note that if the thumbnailPhoto AD attribute is changed, it will not be pushed back to the mailbox. So you can have different photos in both locations
        2. Also note this is lower the recommend size of 96×96 pixels
        3. Exchange 2010 users and any application that isn’t aware of or can’t connect to the Exchange 2013 mailbox of a user who will default to the thumbnailPhoto attribute in AD
      4. Pictures can be uploaded directly by users through Outlook Web Access, this can be disabled
      5. The 2013 Lync client and SharePoint 2013 will attempt to pull the high resolution picture from the mailbox 1st before falling back to the thumbnailPhoto This can happens in instances when Exchange is unavailable to those applications
        1. Exchange can automatically resize the photo stored in the mailbox as needed for any given application that accesses it

 

This attribute can be populated via the following methods:

  1. Exchange cmdlets (multiple methods)
    1. Set-UserPhoto USERNAME -PictureData ([System.IO.File]::ReadAllBytes("C:\Photos\USERNAME.jpg"))
    2. Import-RecipientDataProperty -Identity USERNAME -Picture -FileData ([Byte[]]$(Get-Content -Path "C:\Photos\USERNAME.jpg" -Encoding Byte -ReadCount 0))

Working with Photos

  1. Using the Exchange cmdlets in the Exchange Management console (EMS)
    1. Verify that a mailbox has a photo
      1. (Get-mailbox USERNAME).HasPicture
    2. Remove a user’s photo using the following command
      1. Remove-UserPhoto USERNAME
    3. Export the photo in a mailbox
      1. (Get-UserPhoto USERNAME).pictureData | ForEach { $_ | Add-Content C:\temp\USERNAME.jpg -Encoding Byte}
      2. (Export-RecipientDataProperty -Identity USERNAME –Picture).FileData | ForEach { $_ | Add-Content C:\temp\USERNAME.jpg -Encoding Byte}
    4. Via Exchange Webservices (EWS)
      1. Get a user’s photo (using various file sizes)
        1. https://MAIL.contso.com/ews/Exchange.asmx/s/GetUserPhoto?email=FIRSTNAME.LASTNAME@msx.bala.susq.com&size=HR648x648
        2. https://MAIL.contso.com /ews/Exchange.asmx/s/GetUserPhoto?email=FIRSTNAME.LASTNAME@msx.bala.susq.com&size=HR48x48
      2. Here are all the supported resolutions
        • 48×48
        • 64×64
        • 96×96
        • 120×120
        • 240×240
        • 360×360
        • 432×432
        • 504×504
        • 648×648

Links

Posted in Uncategorized | Leave a comment

Using SHA512 SSL certs with Exchange 2013 on Windows Server 2012 R2 breaks TLS at lower OS rollup levels

We use and internal certificates in my company for Exchange 2013 and recently we employed a company wide mandate to move all internal SSL certificates from SHA1 to SHA512. Our current company patching policy is to apply security patches and only install other patches on an as needed basis. When the time came to renew our SHA1 cert for Exchange 2013 we discovered that SMTP fails when using TLS 1.2 with a SHA512 certificate on windows 2012 R2 (and possibly Server 2008 R2).  There are two options to fix this situation

  1. Install the August 2014 update rollup which enables SHA512 for TLS 1.2
  2. Disable TLS 1.2 via the registry, this forces TLS 1.1 (a weaker protocol) and also breaks windows update
    1. Over all this a solution that should be avoided, but it’s nice to know it works in a pinch

I’ve tested both successfully in my environment and in the end we went with the update.

Posted in Exchange, Exchange 2013 | Leave a comment

Email messages with a blank X-OriginatorOrg header will repeatedly crash the FrontEndTransport Service in EX2013 CU8+

My company recently ran into this issue 2 weeks ago and confirmed with MS that it affects Exchange 2013 CU8, CU9, and CU10 (Exchange 2016 is fine). Basically any message that contains an X-OriginatorOrg header with a null or just white spaces will cause The FrontEndTransport Service to Crash. As long as that header contains any other info it’s fine.
Here is an example of what the message would look like

From: "Student Loan Notice"
MIME-Version: 1.0
To:
Subject: Forgiving Student Loans is possible
Content-Language: en-us
X-Originating-IP: 162.253.55.77
X-OriginatorOrg:
Content-Type: text/plain; charset=ISO-8859-1

Message body

Once this message is received by the FrontEndTransport service the following two event logs entries will occur. Once stating a messages with an invalid SMTP domain was found

Log Name: Application
Source: MSExchangeFrontEndTransport
Event ID: 1033
Task Category: SmtpReceive
Level: Error
Keywords: Classic
User: N/A
Computer: XCH201301.contoso.com
Description:
An exception was thrown while processing data from client IP address 192.168.250.125. The exception is System.FormatException: "" isn't a valid SMTP domain.
at Microsoft.Exchange.Data.SmtpDomain..ctor(String domain, Boolean check)
at Microsoft.Exchange.Transport.Agent.TrustedMail.InboundTrustAgent.GetOriginatingDomain(EndOfHeadersEventArgs endOfHeadersEventArgs)
at Microsoft.Exchange.Transport.Agent.TrustedMail.InboundTrustAgent.EndOfHeadersHandler(ReceiveMessageEventSource eventSource, EndOfHeadersEventArgs eventArgs)
at Microsoft.Exchange.Data.Transport.Smtp.SmtpReceiveAgent.Invoke(String eventTopic, Object source, Object e)
at Microsoft.Exchange.Data.Transport.Internal.MExRuntime.Dispatcher.Invoke(MExSession session)
at Microsoft.Exchange.Data.Transport.Internal.MExRuntime.MExSession.Invoke()
at Microsoft.Exchange.Data.Transport.Internal.MExRuntime.MExSession.AsyncInvoke(Object state)
at Microsoft.Exchange.Data.Transport.Internal.MExRuntime.MExSession.BeginInvoke(String topic, Object source, Object e, AsyncCallback callback, Object callbackState)
at Microsoft.Exchange.Protocols.Smtp.DataBdatHelpers.RaiseEOHEvent(Object state, ISmtpInSession session, AsyncCallback callback, EndOfHeadersEventArgs eventArgs)
at Microsoft.Exchange.Protocols.Smtp.DataInboundProxySmtpCommand.RawDataReceived(Byte[] data, Int32 offset, Int32 numBytes)
at Microsoft.Exchange.Protocols.Smtp.SmtpInSession.ReadComplete(IAsyncResult asyncResult).

Followed by one entry for the crash of the FrontEndTransport service

Log Name: Application
Source: MSExchange Common
Event ID: 4999
Task Category: General
Level: Error
Keywords: Classic
User: N/A
Computer: XCH201301.contoso.com
Description:
Watson report about to be sent for process id: 87600, with parameters: E12IIS, c-RTL-AMD64, 15.00.1076.009, MSExchangeFrontendTransport, M.Exchange.Data, M.E.D.SmtpDomain..ctor, System.FormatException, 6379, 15.00.1076.009.
ErrorReportingEnabled: False

This will continue to happen until the message it removed from whatever upstream source is trying to deliver it to your Exchange server. MS has identified it as a bug and delivered us an out of band patch that applies to CU10 but can’t be applied to CU11. MS has told us that the fix will be included in CU12.

I originally posted this issue in the Exchange subreddit, any updates will be posted there.

Posted in Exchange, Exchange 2013 | Leave a comment

PowerShell script to download attachments from an email

Recently I was asked to automate the process of grabbing an email from a mailbox and downloading all the attachments to a specified destination. The following script accomplishes this using the Exchange Managed Webservices API. A few notes about this script:

  1. It must be run by either the same account that owns the mailbox being searched or an account with the impersonation RBAC role assigned to it
  2. It requires the EWS API, and you can specify the path to your installed version
  3. The Script searches for any email with a similar supplied subject
  4. Optionally the script can do the following:
    1. Do an exact search for the subject supplied
    2. Delete the email after a successful download of all the attachments
    3. Can be set not to overwrite files with the same name in the target directory
    4. If the attachments are zip files it can extract the files to the specified location (does not work with overwrite protection)
    5. Search for only emails matching today’s date
    6. Send an email error report to a specified email (good if the script is going to be run through a simple scheduler like Scheduled Tasks

This script currently cannot download attached EML/MSG files or embedded attachments in those files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
<#
.SYNOPSIS
Get-AttachmentFromEmail.ps1 will use Exchange Web Services to search the inbox of a given mailbox associated with an SMTP Address for any emails with attachments that are similar to the subject specified. If found all attachments in the emails found will be saved to the specified path. Options include the ability to search for just emails that arrived today, a search for an exact subject match, the ability to automatically unzip *.zip files, and the ability to delete the emails once the attachments have been successfully downloaded. The script also supports using impersonation to access a mailbox not belonging to the run time user
.DESCRIPTION
Before attempting any work the script checks for the existence of the EWS managed API, if it cannot be found the script will send an error to the console and to the email address specified to receive error reports
Once the EWS managed API is loaded a connection to Exchange is made to the mailbox of the current runtime user or using impersonation to connect to a mailbox of another user. Once connected the total items of in the mailbox being worked is found, this will be used to ensure the entire inbox is searched when looking for the email in question.
Then a search query is built to look for the following
1. Any email with a subject similar to the subject specified
a. The –ExactSearch parameter will search for emails with a subject that exactly matches the one specified
2. That also has attachments
This search will return all emails that match this query in the inbox, conversely the –TodayOnly switch can be used to return only emails matching the runtime date (e.g. 10/1/2013)
If any emails are found then the attachments are saved to the specified path (overwriting any files with the same name), if the path is not accessible then the script will send an error to the console and to the email address specified to receive error reports.
If the switch –UnZipFiles is used and the email attachments are indeed zip files then the script first copy the zip files to the destination path specified, un-compress the contents, and delete the zip file
If the switch –DeleteEmail is used then after all the attachments have been downloaded the emails found will be moved to the Deleted folder on the mailbox in question. 
.PARAMETER EmailSubject
The exact subject of the email that the script will search for
.PARAMETER SavePath
The local or network path the attachments found will be save to
.PARAMETER SMTPAddress
The SMTP address of the of the mailbox that the script will search for regardless if it's the current runtime user or a different user
.PARAMETER DeleteEmail
If specified any email found and it’s attachments successfully saved will be moved to the deleted folder. 
.PARAMETER TodayOnly
If specified only emails found that match the Day, Month, and Year of the current script runtime will be returned by the inbox search 
.PARAMETER ExactSearch
By default the script will search for any email matching any of the terms in the subject being searched for, when using this parameter the script will look for emails with a subject that exactly matches the subject being searched for
.PARAMETER UnZipFiles
If any attachments found are zip files you can specify that the script extract the files within the zip file and store them at the specified location instead of the zip file itself
.PARAMETER EwsUrl
Instead of using auto discover you can specify the EWS URL
.PARAMETER ExchangeVersion
Specify the Exchange Version the EWS service should use, the default is "Exchange2010_SP2"
.PARAMETER IgnoreSSLCertificate
Used to ignore any SSL certificate errors encountered when using EWS
.PARAMETER EWSManagedApiPath
Used to specify the path for the EWS Managed API, the default is C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll
.PARAMETER EWSTracing
Used to turn on EWS tracing for troubleshooting
.PARAMETER ImpersonationUserName
The Username of the account to user for impersonation
.PARAMETER ImpersonationPassword
The Password of the account to user for impersonation
.PARAMETER ImpersonationDomain
The Domain of the account to user for impersonation
.PARAMETER EmailFrom
The SMTP address error emails will come from
.PARAMETER EmailErrorsTo
The SMTP address error emails will go to
.PARAMETER SMTPServer
The SMTP address server used to send error emails 
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Important Attachment” –SavePath “\\FileServer\Email Attachments” -SMTPAddress John.Doe@company.com
 
Description
-----------
Will use the runtime account to access and search the mailbox associated with "John.Doe@company.com" for any emails in the inbox with a subject like “Important Attachment” and save the attachments to \\FileServer\Email Attachments
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Important Attachment” –SavePath “\\FileServer\Email Attachments” -SMTPAddress John.Doe@company.com -ExactSearch –UnZipFiles 
 
Description
-----------
Will use the runtime account to access and search the mailbox associated with "John.Doe@company.com" for any emails in the inbox with the exact subject of “Important Attachment” and save the attachments to \\FileServer\Email Attachments. If any of those attachments are zip files then the script will extract the contents of the zip files leaving only the contents and not the zip file
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Sales Results” –SavePath “C:\Email Attachments” -SMTPAddress John.Doe@company.com -DeleteEmail -TodayOnly 
 
Description
-----------
Will use the runtime account to access and search the mailbox associated with "John.Doe@company.com" for any emails in the inbox with a subject like “Sales Results” with the runtime date of today and save the attachments to \\FileServer\Email Attachments. Once the attachments have been saved then move the email to the delete items folder
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Important Attachment” –SavePath \\FileServer\Email Attachments -SMTPAddress differentUser@company.com –ImpersonationUserName ServiceMailboxAutomation –ImpersonationPassword “$*fnh23587” –ImpersonationDomain CORP
 
Description
-----------
Will search the mailbox associated with “differentUser@company.com” using the account “ServiceMailboxAutomation” which will need the impersonation RBAC role to access the mailbox. The search will be for any emails in the inbox with a subject like “Important Attachment” and save the attachments to \\FileServer\Email Attachments. 
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Important Attachment” –SavePath \\FileServer\Email Attachments -SMTPAddress John.Doe@company.com –EmailFrom EmailTeam@company.com –EmailErrorsTo HelpDesk@company.com –SMTPServer mail.company.com
 
Description
-----------
Will use the runtime account to access and search the mailbox associated with "John.Doe@company.com" for any emails in the inbox with a subject like “Important Attachment” and save the attachments to \\FileServer\Email Attachments. If any errors are encountered then send an email from “EmailTeam@company.com” to “HelpDesk@company.com” using the SMTP server of “mail.company.com”
.EXAMPLE
PS C:\> .\Get-AttachmentFromEmail.ps1 -EmailSubject “Important Attachment” –SavePath \\FileServer\Email Attachments -SMTPAddress John.Doe@company.com –EwsUrl https://webmail.company.com/EWS/Exchange.asmx –EWSManagedApiPath "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll" -$ExchangeVersion Exchange2010_SP1 –IgnoreSSLCertificate -EWSTracing
 
Description
-----------
Will use the runtime account to access and search the mailbox associated with "John.Doe@company.com" any emails in the inbox that exactly match “Important Attachment” and save the attachments to \\FileServer\Email Attachments. Before connecting to the mailbox the EWS connection will use the following options
1. The EWS URL of https://webmail.company.com/EWS/Exchange.asmx
2. The EWS Managed API Path of "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
3. The Exchange version of "Exchange2010_SP1"
4. Ignore all SSL Certificate errors
5. Turn on EWS tracing
.INPUTS
System.String
You cannot pipe to this script
.OUTPUTS
NONE
.NOTES
AUTHOR: John Mello 
CREATED : 10/29/2013 
CREATED BECAUSE: To automate the retrieval, download, and deletion of a daily delivered email attachment 
.LINK
DSMS Script Storage location : \\Bala01\World\Technology\EnterpriseServices\PlatformServices\Directory and Messaging Services\Scripts
DSMS SharePoint Scripting Portal : http://techweb/ess/dci/dsms/scripting/default.aspx
DSMS PowerShell KB : http://techweb/ess/dci/dsms/scripting/powershellscripting/Home.aspx
#>
[CmdletBinding(DefaultParameterSetName="Default")]
Param(
[Parameter(Mandatory=$True,Position=0)]
[string]$EmailSubject,
 
[Parameter(Mandatory=$True,Position=1)]
[string]$SavePath,
 
[Parameter(Mandatory=$True,Position=3)]
[string]$SMTPAddress,
 
[Parameter(Mandatory=$false)]
[switch]$DeleteEmail,
 
[Parameter(Mandatory=$false)]
[switch]$TodayOnly,
 
[Parameter(Mandatory=$false)]
[switch]$ExactSearch,
 
[Parameter(Mandatory=$false)]
[switch]$UnZipFiles,
 
[Parameter(Mandatory=$false)]
[string]$EwsUrl = "https://webmail.susq.com/EWS/Exchange.asmx" ,
 
[Parameter(Mandatory=$false)]
[ValidateSet("Exchange2007","Exchange2007_SP1","Exchange2007_SP2","Exchange2007_SP3","Exchange2010","Exchange2010_SP1","Exchange2010_SP2","Exchange2010_SP3")]
[string]$ExchangeVersion = "Exchange2010_SP2",
 
[Parameter(Mandatory=$false)]
[switch]$IgnoreSSLCertificate,
 
[Parameter(Mandatory=$false)]
[string]$EWSManagedApiPath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll",
 
[Parameter(Mandatory=$false)]
[switch]$EWSTracing,
 
[Parameter(Mandatory=$True,ParameterSetName="Impersonation")]
[string]$ImpersonationUserName,
 
[Parameter(Mandatory=$True,ParameterSetName="Impersonation")]
[string]$ImpersonationPassword,
 
[Parameter(Mandatory=$false,ParameterSetName="Impersonation")]
[string]$ImpersonationDomain,
 
[Parameter(Mandatory=$False)] 
[string]$EmailFrom, 
 
[Parameter(Mandatory=$False)] 
[string[]]$EmailErrorsTo,
 
[Parameter(Mandatory=$False)] 
[string]$SMTPServer = "mailhost.susq.com"
)
 
#Region Functions
 
Function New-EWSServiceObject {
<#
.SYNOPSIS
Returns an EWS Service Object
.DESCRIPTION
Creates a EWS service object, with the option of using impersonation and/or An EWS URL or fall back to Autodiscover
.PARAMETER SMTPAddress
The SMTP address of the Exchange mailbox that is associated with the EWS object
.EXAMPLE
PS C:\powershell> New-EWSServiceObject -SMTPAddress "John.Doe@Company.com"
 
------------------
Description 
------------------
 
This will return and EWS object that uses impersonation with a specifed URL
#>
[CmdletBinding(DefaultParameterSetName="OtherUser")]
Param() 
 
Write-Verbose "Creating EWS Service connection object"
$EWSService = new-object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::$ExchangeVersion)
 
If ($EWSTracing) {
Write-Verbose "EWS Tracing enabled"
$EWSService.traceenabled = $true
}
 
if ($IgnoreSSLCertificate){
Write-Verbose "Ignoring any SSL certificate errors"
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true };
} 
 
If ($SMTPAddress) {Write-Verbose "Creating service for the following address $SMTPAddress"}
Else {Write-Verbose "Creating service for the following runtime user $ENV:UserName"} 
 
Write-Verbose "Checking if the runtime or a seperate account will be used for impersonation"
If ($ImpersonationUserName -and $ImpersonationPassword) {
Write-Verbose "Secondary account for Impersonation specifed ($ImpersonationUserName)"
If ($ImpersonationDomain) {
#If a domain is presented then use that as well
$EWSService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($ImpersonationUserName,$ImpersonationPassword,$ImpersonationDomain)
}
Else {
#Otherwise leave the domain blank
$EWSService.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials($ImpersonationUserName,$ImpersonationPassword)
}
Write-Verbose "Saving impersonation credentials for EWS service"
$EWSService.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $SMTPAddress)
}
Else{
Write-Verbose "Runtime account specifed for impersonation ($ENV:Username)"
$EWSService.UseDefaultCredentials = $true 
}
 
#Set the EWS URL, the EWS URL is needed if the the runtime user is specifed since they may not have a mailbox
If ($EWSURL) {
Write-Verbose "Using the specifed EWS URL of $EWSURL"
$EWSService.URL = New-Object Uri($EWSURL)
}
Else {
Write-Verbose "Using the AutoDiscover to find the EWS URL"
$EWSService.AutodiscoverUrl($SMTPAddress, {$True})
}
#Now Return the Service Object
Return $EWSService
}
 
Function Send-ErrorReport {
<#
.SYNOPSIS
Used to create a one line method to write an error warning to the console, send an error email, and exit a script when an terminal error is encountered
.DESCRIPTION
Send-ErrorReport Takes a Subject and message body field and uses the Subject to write a warning messages to the console and as the email subject. It uses the body as the body of the email that will be sent. You can also specify and SMTP Server, From, and To address or set the default options. Once complete the script sends the exit command to script calling the function 
.PARAMETER Subject
The subject of the email to be sent and the warning message that is sent to the console
.PARAMETER body 
The body of the email sent
.PARAMETER HaltScript
Sends the Exit command to the script caling the function, used to report on terminating errors
.EXAMPLE
PS C:\powershell> Send-ErrorReport -Subject "can't load EWS module" -Body "can't load EWS module, verify this path : $EWSManagedApiPath" -HaltScript
 
WARNING: can't load EWS module
 
------------------
Description 
------------------
 
This will send an email through the specifed SMTP server, from and to the specifed addresses with the specifed subject and body and use the sbubject to write a warning message. Then function will stop the script that called it
#>
[CmdletBinding()]
Param(
[Parameter(Position=0,Mandatory=$true)]
[string]$Subject,
 
[Parameter(Position=1,Mandatory=$true)]
[string]$body,
 
[Parameter()]
[switch]$HaltScript
) 
 
Write-Warning $Subject
#Appened Script name to email Subject
If ($EmailFrom -and $EmailErrorsTo -and $SMTPServer) {
$Subject = "Get-AttachmentFromEmail.ps1 : " + $Subject
send-mailmessage -from $EmailFrom -to $EmailErrorsTo -smtpserver $SMTPServer -subject $Subject -Body ($body | Out-String) -BodyAsHtml
}
If ($HaltScript) {Exit 1}
}
 
#EndRegion
 
#Region PreWork
 
#Remove double qoutes from Subject, File Path, and SMTP address (just in case)
#Need to find a way around this
$EmailSubject = $EmailSubject -replace "`""
$SavePath = $SavePath -replace "`""
$SMTPAddress = $SMTPAddress -replace "`""
 
# Check if the save path is available, if not then exit the script
Try {Test-Path $SavePath -ErrorAction Stop | Out-Null}
Catch {Send-ErrorReport -Subject "Save path cannot be accessed" -body "Please the following user name <B>$($ENV:USERNAME)<?B>, has access to this path : <B>$SavePath</B>" -HaltScript}
 
# Check if EWS Managed API available, if not then exit the script
Try {Get-Item -Path $EWSManagedApiPath -ErrorAction Stop | Out-Null}
Catch {Send-ErrorReport -Subject "EWS Managed API path cannot be accessed" -body "Please verify the following EWS API path on <B>$($ENV:COMPUTERNAME)</B> : <B>$EWSManagedApiPath</B>" -HaltScript}
 
# Load EWS Managed API
[void][Reflection.Assembly]::LoadFile($EWSManagedApiPath);
 
#EWS requires double back whacks "\\" for each normal back whack "\" when
#it comes to the file path to save to
#E.g. C:\Windows\System32 needs to look like C:\\Windows\\System32
$EWSSavePath = $SavePath -replace "\\","\\"
 
#Create EWS Service
$EWSservice = New-EWSServiceObject
#EndRegion
 
#Region Main Program Work
#Attach to the inbox to find the total number of items
#This will be used on in the search query so that we search the entire inbox
$InboxID = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
Try {$InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($EWSservice,$InboxID)}
Catch {Send-ErrorReport -Subject "Account is not permissioned for Impersonation" -body "Please verify that the following account <B>$ImpersonationUserName</B> has the ability to impersonate <B>$SMTPAddress</B>" -HaltScript}
 
$NumEmailsToReturn = $InboxFolder.TotalCount
If ($InboxFolder.TotalCount -eq 0) {
Write-Warning "Inbox is empty, exiting script or the Runtime Account of $($ENV:USERNAME) does not have impersonation rights for $SMTPAddress"
Exit
}
 
#Create mailbox view
$view = New-Object -TypeName Microsoft.Exchange.WebServices.Data.ItemView -ArgumentList $NumEmailsToReturn
#Define properties to pull for each item in the view
$propertyset = New-Object Microsoft.Exchange.WebServices.Data.PropertySet (
[Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::HasAttachments,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::DisplayTo,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::DisplayCc,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeSent,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived
)
#Assign view to porperty set
$view.PropertySet = $propertyset
#Define the search quuery
#An EWS exact search puts the search term in "" so if we need that then add the qoutes again)
If ($ExactSearch) {
$EmailSubject = "`"$EmailSubject`""
}
If ($TodayOnly) {$query = "Subject:$EmailSubject AND HasAttachments:True AND Received:today"}
Else {$query = "Subject:$EmailSubject AND HasAttachments:True"}
 
#Preform the search
$FoundEmails = $EWSservice.FindItems("Inbox",$query,$view)
#$FoundEmail = $items | Where-Object {$_.Subject -like $EmailSubject}
If ($FoundEmails) {
If ($UnZipFiles) {$ZipFileNames = @()}
Foreach ($Email in $FoundEmails) {
$emailProps = New-Object -TypeName Microsoft.Exchange.WebServices.Data.PropertySet(
[Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly,
[Microsoft.Exchange.WebServices.Data.ItemSchema]::Attachments
)
 
$EmailwithAttachments = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($EWSservice, $Email.Id, $emailProps)
Foreach ($File in $EmailwithAttachments.Attachments) {
Try {
#Just to be safe, remove any invaild characters from the attachment name
$FileName = $File.name -replace ("[{0}]" -f ([RegEx]::Escape([String][System.IO.Path]::GetInvalidFileNameChars())))
#Current can't handle Emails that are attacments, so we skip them
If ($File.contenttype -eq $null) {
Write-Warning "Attachment is an email, skipping"
$EMLAttachment = $TRUE
continue
}
Else {$EMLAttachment = $FALSE}
$File.load($EWSSavePath + "\\" + $FileName)
If (($FileName -like "*.zip") -and $UnZipFiles) {$ZipFileNames += $SavePath + "\"+ $FileName}
}
Catch {Send-ErrorReport -Subject "Attachment save path cannot be accessed" -body "Please verify the following path <B>$SavePath</B><BR>Full Error:<BR> $_" -HaltScript}
}
If ($DeleteEmail -and (-not $EMLAttachment)) {$Email.Delete("MoveToDeletedItems")}
Else {Write-Warning "DeleteEmail specifed but embedded EML file in email could not be downloaded"}
}
If ($UnZipFiles) {
Try {
$shell = new-object -com shell.application
$Location = $shell.namespace($SavePath)
foreach ($ZipFile in $ZipFileNames)
{
$ZipFolder = $shell.namespace($ZipFile)
$Location.Copyhere($ZipFolder.items())
Remove-item $ZipFile
}
}
Catch {Send-ErrorReport -Subject "Attachment save path cannot be accessed" -body "Please verify the following path <B>$SavePath</B><BR>Full Error:<BR> $_" -HaltScript}
}
}
#EndRegion
Posted in Email, EWS, Exchange | Leave a comment