For a long time now I’ve wanted to write a script that would automatically generate email traffic within an Exchange Server test lab environment.

Having realistic email traffic within a test lab environment means you can do such real world activities as:

  • test backup and recovery scenarios
  • learn how to use message tracking logs
  • test archiving solutions

In the past I’ve used some simple VBScripts that just sent random messages via SMTP as a way to fill up test lab mailboxes. That approach had some disadvantages though. The scripts I wrote only sent a stream of email messages at a single rate rather than at varying rates through the day as you would see in the real world. They also filled up inboxes only, never putting the messages in the Sent Items folder for the From address.

So I got to work creating a new PowerShell script to generate the email traffic. I tracked some of the development in the forums and can now share the complete script here.

This script does require some setting up before you run it, so please read the instructions to get it working in your test lab. I have only written and tested this script for Exchange 2010 training lab environments on the assumption that most people will be training for the latest version of Exchange.

Before we go further let me be absolutely clear that this script is for test lab environments only. Under no circumstances should you attempt to run this script in a production environment.

Using the Start-MailGen.ps1 Script in Your Test Lab

The scripts uses the Exchange Web Services Managed API so the first step is to download and install that on your test lab server.

EWS Managed API
EWS Managed API

Next, download the script and extract the three files to your server. I placed mine in C:ScriptsMailGen.

Download the script files from Github.

Open the Start-MailGen.ps1 file in the PowerShell editor or in Notepad and check the following items.

The $dllfolderpath variable is set to the default installation path for the EWS Managed API v2.0. If you install a different version, or to a different path, update this variable.

#Path to the Exchange Web Services DLL
$dllfolderpath = "C:Program FilesMicrosoftExchangeWeb Services1.1Microsoft.Exchange.WebServices.dll"

The script uses a switch statement to determine how many emails to send each hour of the day. These values are what I use but you can change them up or down to suit your test lab. The hours 6am to 7pm are individually specified, and then the default value at the end is used for the remaining hours of the day.

06 {$sendcount = 50}
07 {$sendcount = 80}
08 {$sendcount = 600}
09 {$sendcount = 600}
10 {$sendcount = 800}
11 {$sendcount = 1000}
12 {$sendcount = 600}
13 {$sendcount = 600}
14 {$sendcount = 800}
15 {$sendcount = 800}
16 {$sendcount = 900}
17 {$sendcount = 400}
18 {$sendcount = 200}
19 {$sendcount = 80}
default {$sendcount = 10}

You can just specify even numbers like the above because the script varies the send count further by adding a random number each time. This will give you a realistic level of email traffic through the different hours of the day.

Sample email traffic graph
Sample email traffic graph

The service account that will be running the script needs to have its own mailbox, and also have impersonation rights granted to it. I run mine as Administrator since it is just a test lab. Open the Exchange Management Shell and run the following command to grant the impersonation rights.

[PS] C:\>New-ManagementRoleAssignment -Name:impersonationAssignmentName -Role:ApplicationImpersonation -User:administrator

You may also need to set your script execution policy to unrestricted.

[PS] C:\>Set-ExecutionPolicy Unrestricted

Also, as the script file was downloaded from the internet you may need to right-click the file and choose Properties, and then click the Unblock button.

The script also depends on the Active Directory remote administration tools. These should be installed already on an Exchange 2010 mailbox server, but if you’re running the script from a non-Exchange server you may need to install them.

Finally, to start generating email traffic open the Exchange Management Shell and run the script.

[PS] C:ScriptsMailgen>.Start-MailGen.ps1

The script begins to send email and will show a progress indicator.

Start-MailGen.ps1 running
Start-MailGen.ps1 running

The script will select a random sender and recipient from the available mailboxes and distribution groups in your test lab environment, and then construct a random email message using the two files that are provided with the script.

After sending the applicable number of emails for that hour of the day the script will sleep for 5 minute blocks until it reaches the next hour, and will start sending again.

You can leave the script running for several days if you wish, or set it as a scheduled task to ensure that it starts up again if the server is rebooted.

How to Hard-Code the EWS URL

A few people have seen Autodiscover errors in their test lab and, if they have verified that Autodiscover is otherwise working fine, may need to look at hard-coding the EWS URL in the script. To do so find the following line and comment it out with the hash character:

#$service.AutodiscoverUrl($user.Properties.mail)

Now add a new line below it with the following:

$service.Url = "https://ho-ex2010-mb1.exchangeserverpro.net/EWS/Exchange.asmx"

Replace the URL above with the appropriate server FQDN for your own server environment.

About the Author

Paul Cunningham

Paul is a former Microsoft MVP for Office Apps and Services. He works as a consultant, writer, and trainer specializing in Office 365 and Exchange Server. Paul no longer writes for Practical365.com.

Comments

  1. matan

    Hi Paul,
    tried this script on an EX 2016 (2 servers) in a test domain (no internet connectivity)
    when i run it i get this error on all mailboxes:

    Exception calling “SendAndSaveCopy” with “0” argument(s): “The request failed. The underlying connection was closed: Could not establish trust relationship for the SSL/TLS se
    cure channel.”
    At D:\sources\Start-MailGen\Start-MailGen.ps1:296 char:5
    + $mail.SendAndSaveCopy()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceRequestException

    any help will be most appreciated/
    thnx.

  2. Patrique

    Hi Paul,

    Thank you for the script. Today I have installed the ExchangeServer2016-x64-CU19 version.

    Do you have an idea about the error?

    Exception calling “SendAndSaveCopy” with “0” argument(s): “The request failed. The remote server returned an error:
    (401) Unauthorized.”
    At C:\EmailGen\Start-MailGen.ps1:301 char:5
    + $mail.SendAndSaveCopy()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceRequestException

  3. Dino Cinquegrani

    Great script…This along with the AD Starwars Powershell Module, https://itfordummies.net/2017/08/21/active-directory-star-wars-powershell-module/ i was able to completly build en exchange test environment. Confirmed this works in Exchange 2016 CU17, sortof. the script runs through several iterations before failing with each message with the following error.

    Exception calling “SendAndSaveCopy” with “0” argument(s): “The request failed. The remote server returned an error:
    (401) Unauthorized.”
    At C:\temp\mailgen\Start-MailGen.ps1:301 char:5
    + $mail.SendAndSaveCopy()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceRequestException

    if i pause the script and wait a few hours, and start it, it works again, for a while.

  4. Rainier

    Would get an impersonation error if running psh shell as administrator, so had to ‘Run-as my service account (sender) account.

    Then script would run but hang at Subject…

    [PS] C:\Scripts\MailGen>.\Start-MailGen.ps1
    Preparing EWS
    Starting email generation loop
    *** Will send 14 emails this hour
    Retrieving recipient list
    1 mailboxes found
    0 distribution groups found
    1 total recipients found
    *** New email message
    Sender: mailbot@wacketywack.local
    Subject: Parley

    Turns out my sender could only see its own mailbox when enumerating recipients.

    Found Exchange creates an Active Directory Security Group called View-Only Organization Management which you have to add your service account to.

    Members of this group can view the properties of all objects in your Exchange 2010 environment, so can list all the mailboxes on a given server.

    1. Matan

      i’m having the same problem with the impersonation. can you please explain what exactly did you do?
      what do you mean “run-as my service account”? did you create service account? what permissions you gave it?
      please explain the steps…this error is killing me here.
      (exchange 2016)
      thank you.

  5. Rainier Amara

    Would get an impersonation error if running psh shell as administrator, so had to ‘Run-as my service account (sender) account.

    Then script would run but hang at Subject…

    [PS] C:\Scripts\MailGen>.\Start-MailGen.ps1
    Preparing EWS
    Starting email generation loop
    *** Will send 14 emails this hour
    Retrieving recipient list
    1 mailboxes found
    0 distribution groups found
    1 total recipients found
    *** New email message
    Sender: mailbot@wacketywack.local
    Subject: Parley

    Turns out my sender could only see its own mailbox when enumerating recipients.

    Found Exchange creates an Active Directory Security Group called View-Only Organization Management which you have to add your service account to.

    Members of this group can view the properties of all objects in your Exchange 2010 environment, so can list all the mailboxes on a given server.

  6. devraj

    Dear Paul,

    I want to generate an e-mail traffic of 50,000 e-mails for 20, office 365 users.
    I had used multi threading to reduce the time to generate traffic, where number of threads will be number of users, in my case it is 20 threads.
    I had used the concepts from Start-MailGen.ps1 and the SendMail function in Start-MailGen.ps1 is added as a runspace script as shown below:

    $Jobs = @()

    foreach ($user in $Users) {
    $Job = [powershell]::Create().AddScript($SendMail).AddParameter(“sender”, $user)
    $Job.RunspacePool = $RunspacePool
    $Jobs += New-Object PSObject -Property @{
    RunNum = $_
    Job = $Job
    Result = $Job.BeginInvoke()
    }
    }

    Could you please look into this code snippet and let me know what is wrong here as this script runs fine, but No emails are generated.

    With Regards,
    Devraj

  7. Jan

    Hi Paul,

    thank you for that script, it is very usefull. I have some troubles like guys here had.
    Hardcoded EWS url and Exception calling “SendAndSaveCopy” with “0” argument(s): “The Url property on the ExchangeService object must be set.”.

    I have problem that i change EWS url from https://ex1.domain.local/EWS/Exchange.asmx to https://mail.domain.com/EWS/Exchange.asmx .

    I also change certificate from self signed to wildcard for all services. It is problem, if i define URL with domain mail.domain.com and wildcard certificate it doesnt work.

    If I use ex1.domain.local with non wilcard certificate it works. I tested self signed and also SAN certificate.

    I am testing it on EX2013 CU23. If you have an idea why it have this problem share it please.

    Thans Jan

  8. Masoud

    HI

    when i run script i face to this Error :

    Exception calling “SendAndSaveCopy” with “0” argument(s): “The account does not have permission to impersonate the requested user.”

    i have exchange 2016 and windows server 2012 r2 and it is just the only mail sever in lab, i upgrade exchange server form CU5 to CU9 successfully

    So for solving this problem i Done steps as you said

    1-i Checked mailbox Owner an run this script by owner user
    2-i had impersonation rights granted to user (Owner – User that use for exchange installation)

    so i checked all step one by one. but i still see that problem , what should i have to do?

    thanks for your help Mr Paul

  9. Chris

    This rocks! thank you very much.

  10. Scott C

    I know this is probably a silly question…but will this script work on an Exchange 2007 SP3 running on Windows Server 2003 R2 x64?

  11. Daniel

    Works perfectly on Exchange 2016 CU 5, thank you very much Paul!

  12. VM

    Hi Paul,
    I could fix the above issue by hardcoding EWS url as you mnetioned above. Thank you!

    One more question:
    The script is executing fine and the mails are being sent sucessfully. But I do not see any data on the DB yet? the DB size is not changing at all. I have mentioned the correct DB for the mailboxes.

    Any suggestions?

    Thanks,
    Venku

  13. VM

    Hi Paul,

    I am seeing the below error:

    Exception calling “SendAndSaveCopy” with “0” argument(s): “The request failed. Unable to connect to the remote server”
    At C:\Scripts\Start-MailGen\Start-MailGen.ps1:296 char:5
    + $mail.SendAndSaveCopy()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceRequestException

    Any suggestions?

    Thanks,
    VM

  14. VM

    Hi Paul,

    I am seeing the below error:

    Exception calling “SendAndSaveCopy” with “0” argument(s): “The request failed. Unable to connect to the remote server”
    At C:\Scripts\Start-MailGen\Start-MailGen.ps1:296 char:5
    + $mail.SendAndSaveCopy()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceRequestException

    Any suggestions?

    Thanks,
    VM

  15. farukh

    Great Work .

  16. Jeremiah

    Morning Paul,

    Thank you for the script, works great and well documented. I am running an issue in my TEST lab though:

    All servers are VM’s and are running Windows Server 2012 R2 (all updates)
    1) Exchange 2013 CU11 (all updates per Windows update)
    2) Outlook 2013 Professional (all updates)

    The script appears to start working but errors when trying to use SendAndSaveCopy with the following error:

    xception calling “SendAndSaveCopy” with “0” argument(s): “This operation is not supported for a relative URI.”
    At C:AMailGen1ModdedMailGen01.ps1:346 char:5
    + $mail.SendAndSaveCopy()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException

    I have followed this article but no luck so far. Any suggestions?

    Thanks!

    Jeremiah

  17. Pallavi

    Hi Paul, I have setup 2 Exchange server 2016 in my testing lab. I am following and able to setup running this test on one Exchange server. However I am running following issue on second exchange server.
    Can you please point out what should I take a look?

    Preparing EWS
    Exception calling “AutodiscoverUrl” with “1” argument(s): “The Autodiscover service couldn’t be located.”
    At C:scriptsStart-MailGen.ps1:367 char:1
    + $service.AutodiscoverUrl($user.Properties.mail)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : AutodiscoverLocalException

    Starting email generation loop

    *** New email message
    Exception calling “SendAndSaveCopy” with “0” argument(s): “The Url property on the ExchangeService object must be set.”
    At C:scriptsStart-MailGen.ps1:296 char:5
    + $mail.SendAndSaveCopy()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceLocalException

    1. Paul Cunningham

      Maybe Autodiscover isn’t configured, or the account you’re running the script with can’t locate it. Or check the tip at the end of the blog post for hard coding the EWS URL.

  18. Kyle Cherry

    Nice Paul, works well on 2013. I was wondering how I would get some email into a training lab server for backup, perfect.

  19. Darren Wood

    Hi Paul,

    Thanks this is just what I was looking for, come to your site all the time for stuff, your knowledge is well valued by me.

    Thanks for all the effort that you put into helping us Exchange wanabees

  20. RB

    Hi,

    The link on github does not work and cannot download the scripts.

    can I download the script from a different location?

  21. Ram

    Hi Paul
    Exception calling “SendAndSaveCopy” with “0” argument(s): “The Url property on the ExchangeService object must be set.”
    At E:mailGenStart-MailGenStart-MailGen.ps1:296 char:5
    + $mail.SendAndSaveCopy()

    is there anything need to edit in the script

    1. Paul Cunningham

      Autodiscover is probably failing. Try the suggestion at the end of the article.

  22. Ram

    Hi Paul

    PS] E:mailGenStart-MailGen>.Start-MailGen.ps1

    Welcome to the Exchange Management Shell!

    Full list of cmdlets: Get-Command
    Only Exchange cmdlets: Get-ExCommand
    Cmdlets that match a specific string: Help **
    Get general help: Help
    Get help for a cmdlet: Help or -?
    Exchange team blog: Get-ExBlog
    Show full output for a command: | Format-List

    Show quick reference guide: QuickRef
    Tip of the day #65:

    Do you want to create a new management role assignment policy that’s based on an existing policy, but you don’t want to
    include all the management roles? Use the Get-ManagementRoleAssignment cmdlet and pipe the results to the Where cmdlet.
    The Where cmdlet excludes any role assignments that contain the roles you specify. The remaining role assignments are pi
    ped to the New-ManagementRoleAssignment cmdlet. Type:

    New-RoleAssignmentPolicy
    Get-ManagementRoleAssignment -RoleAssignee | Where { ($_.Role -NE “”) -An
    d ($_.Role -NE “”) } | New-ManagementRoleAssignment -Policy
    The Where statement is case-sensitive.

    Then you can apply the new policy to a mailbox using the Set-Mailbox cmdlet:

    Set-Mailbox -RoleAssignmentPolicy

    VERBOSE: Connecting to Tvlsunmbx02.sunoptical.co.in.
    VERBOSE: Connected to Tvlsunmbx02.sunoptical.co.in.
    Preparing EWS
    Starting email generation loop
    *** Will send 684 emails this hour
    Retrieving recipient list
    21 mailboxes found
    0 distribution groups found
    21 total recipients found
    *** New email message
    Sender: sallen@sunoptical.co.in
    Subject: Extant
    Recipient: csimon@sunoptical.co.in
    Exception calling “SendAndSaveCopy” with “0” argument(s): “The Url property on the ExchangeService object must be set.”
    At E:mailGenStart-MailGenStart-MailGen.ps1:296 char:5
    + $mail.SendAndSaveCopy()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceLocalException

  23. Michael Maher

    >>SendAndSaveCopy : Exception calling “SendAndSaveCopy” with “0” argument(s):

    This can also appear if your Exchange support multiple domains.

    For example, when Outlook Web Access if you login as CONTOSOJSmith then you should send this value instead of your email address in the script.

    Michael

  24. Pankaj tambe

    Dear All,

    Can anyone help me out to create a powershell script as per below requirements.
    1. We are planning to add new SMTP address to our existing users and so we want to set auto reply message as per below to all user mailbox.
    2. Script should take user display name with old email id and new email id and set below customize message on each of individual mailboxes
    3. Reply message should be as per below
    4. Script should take all BOLD content from excel sheet and set customize auto reply message to each individual mailboxes

    Dear Sender,

    Please note that my email id has been changed from abc@test.com to xyz@test.com , hence for the please send mail on new email id only…

    Regards,
    ‘User name’

    Note: We are having Exchange 2010 environment

  25. Todd Strelka

    Hello Paul,
    Is there a way to specify a sample file for an attachment and specify specific text in the subject line or body of the message?

    1. Paul Cunningham

      The script is written to randomize the subject, content, and attachments of the emails. You could edit the script so that instead of picking a random value it just uses a value you specify. But if you’re trying to send specific emails, why not just use Send-MailMessage?

  26. Zoltan

    Thanks for the script Paul. Works well on Ex2013 with self-signed default cert after hardcoding the EWS URL, using EWS API v2.0.

    I use your script to generate enough email volume to grow the database beyond a set size, testing a script that sets the maximum database size.

    Being weekend, modified the script to generate 100,000 as opposed to the default of 10.
    I also added some larger documents to be used as attachment to make the database size grow quicker. The script seems to pick up all files randomly in the Attachments folder.

    Excellent script, thanks again.

  27. Jeremy Leleux

    I’m having trouble with the impersonation portion of the script. I have assigned the correct role assignment to a service account, but still getting the following error:

    SendAndSaveCopy : Exception calling “SendAndSaveCopy” with “0” argument(s): “The account does not have permission to im
    personate the requested user.”
    At C:MailGenStart-MailGen.ps1:296 char:26
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    1. Jeremy Leleux

      I had to change my account that I was using. I got it working.

      1. Matan

        would you please explain what do you mean “change my account that I was using”?
        what exactly did you do?
        im having the same problem

  28. JDeek

    i know this article is old… but still best tool out there.

    I’m building a test environment. I’m trying to use your Exchange Traffic Generator. I’ve used it before … always worked wonderfully.

    i hit an error. i’ve been beating my head against the wall for days.

    it has to be something simple.

    Please help

    it’s not like any of the errors i saw on your article.

    when i start Start-MailGen.ps1 … i receive the following error … and then the script continues to run. though no emails are being created.

    Error Message:
    *******************************************************************
    “Import-Module : the specified module ‘ActiveDirectory’ was not loaded because no valid module file was found in any module directory.

    At C”MailGenStart-mailGen.ps1:359 char:1.”
    * Import-Module ActiveDirectory

    **********************************************************
    I checked line 359 … and sure enough it’s “Import-Module ActiveDirectory’

    what is the ActiveDirectory module?
    What could be the problem?
    is there a work around? like hardcoding the URL …

    but what about retrieving the SID?

    Can you help?

    JDeek

    1. Paul Cunningham

      It’s the Active Directory Powershell module and the script depends on it, so it needs to be installed on the server that you’re running the script from.

    2. Shakti

      Open the powershell and run these commands one after the other

      Import-Module ServerManager
      Add-WindowsFeature RSAT-ADDS

    3. Jan

      Install-WindowsFeature RSAT-AD-PowerShell

  29. Pashupathinath

    Hi,
    Thanks for the wonderful script. I am not able to run this script with the following error,

    Exception calling “SendAndSaveCopy” with “0” argument(s): “Exchange Web Services are not currently available for this request because none of the Client Access Servers in thedestination site could process the request.”
    At C:ScriptsStart-MailGen1Start-MailGen-12.ps1:296 char:5
    + $mail.SendAndSaveCopy()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceResponseException

    Please help.

    1. Paul Cunningham

      The most common cause of problems with this script is SSL certificate issues or Autodiscover configuration issues.

  30. Walt

    Found this to work pretty well and cleanly. Windows 2008R2 across the board, Exchange 2010. Just need to make sure to follow all the item in the post, and make sure that either a real cert is applied or do a self cert (here is the MS post for self-cert on the Exchange server itself and it WORKS dead on when you follow it- http://social.technet.microsoft.com/wiki/contents/articles/13916.how-to-use-a-self-signed-certificate-in-exchange-2010.aspx )
    Also in tinkering, tried dumping some attachments into the attachments directory, just collections of things have gathered over time as sample data, and the script will randomly pick attachments you have placed in the Attachments directory. Pretty nice to be able to drop in your own seed data.

  31. Torsten

    Hi Paul,

    thanks for this great script.

    I want to use this at our lab and need to change the script that only one or two users receive the emails. How can I modify the random part to a list of users?

    Thanks and have a nice day!

    Torsten

  32. chpnath

    I’m using these scripts in LAB Environment only.

    These scripts are very useful. These scripts are working very much good in Exchange 2013 SP1 CU5 environment. But facing issues with Exchange 2010 SP3 Rollup9.
    I’m getting the following error, any help is greatly appreciated.

    Exception calling “AutodiscoverUrl” with “1” argument(s): “The Autodiscover service couldn’t be located.”
    At C:Start-MailGen1Start-MailGen-02.ps1:367 char:25
    + $service.AutodiscoverUrl <<<< ($user.Properties.mail)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

  33. Mark

    .start-MailGen script. I received the following error message. Unable to locate Dictionary files C:scriptsdict.csv any help would be very appreciated.

    1. Paul Cunningham

      That file is included in the Zip file and needs to be in the same location as the script.

      1. Mark

        Thanks Paul, I really appreciate your scripts and quick response.

        1. Mark

          Thanks Paul my lab email is functioning….

  34. TKEXCH

    Hi Paul,

    Thanks for such a wonderful script. I am using this for 1-2 day and it is working fine with me.

    Is there any way to specify the mailbox database to send the emails since I do have 5 different exchange database on same exchange server and I would like to have some data generated withing specified exchange database instead all.

    Any help on this would be realy appreciated.

    Thanks

    1. Paul Cunningham

      Modify the line of the script where Get-Mailbox is run to specify just one database.

  35. Pashupathinath

    I’m running the script with Exchange 2010 SP3 server. My exchange deployment is having many exchange servers in the same domain and in same OU. And many of the user mailboxes are registered with other exchange servers which are in not recoverable state.
    Now when I ran the script it is trying to select all the users in the domain whose mailboxes are registered with other exchange servers which are in un-usable state.

    Is there a way to make/tell the script to select users which are registered with particular exchange server only.

      1. Pashupathinath

        Its a purely test environment and I don’t want any distribution groups to be selected for this script to run.

      2. Pashupathinath

        Thanks the scripts are user friendly I was able to customize as per my need.
        I filtered mailbox selections and distribution selections. Now when I ran the script I’m getting the following error,

        Exception calling “SendAndSaveCopy” with “0” argument(s): “The request failed. The underlying connection was closed: C
        uld not establish trust relationship for the SSL/TLS secure channel.”
        At C:ScriptsStart-MailGen1Start-MailGen.ps1:296 char:26
        + $mail.SendAndSaveCopy <<<< ()
        + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException

        I read one the comment saying install certificates. Could you please link me to the certificates from where to download or install from..

      3. Pashupathinath

        Thanks alot. My setup is a test setup.

        These scripts are user friendly and I was able to customize as per my need.

        I filtered mailbox selections and distribution selections. Now when I ran the script I’m getting the following error,

        Exception calling “SendAndSaveCopy” with “0” argument(s): “The request failed. The underlying connection was closed: C
        uld not establish trust relationship for the SSL/TLS secure channel.”
        At C:ScriptsStart-MailGen1Start-MailGen.ps1:296 char:26
        + $mail.SendAndSaveCopy <<<< ()
        + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException

        I read one the comment saying install certificates. Could you please link me to the certificates from where to download or install from..

  36. Pashupathinath

    Thanks for the nice script. I’m running this script on windows 2012 r2 server with exchange 2013
    sp1. Also I’ve installed Microsoft Exchange Web Services Managed API 2.2.

    I’ve ran the script while following your instructions and I got the following error message,

    “Unable to locate Exchange Web Services DLL”

    Please correct me where I’m doing wrong.

    1. Paul Cunningham

      You need to update the $dllfolderpath variable in the script to point to the correct DLL location. This is explained in more detail in the instructions in the article above.

      1. Pashupathinath

        Thanks Paul, So timely response.

        It resolved my issue.

        Thanks a lot

  37. Dixon

    I keep getting the following error on an Exchange 2010/2013 mixed testing environment. I’m running this as the domain administrator which has a mailbox enabled account. Also, I’ve given full access to the mailboxes in the test environment, set the impersonation account to the administrator, and manually set the EWS url in the script. Any ideas what may be causing this?

    Exception calling “SendAndSaveCopy” with “0” argument(s): “The request failed. The remote server returned an error:
    (401) Unauthorized.”
    At C:ScriptsStart-MailGen.ps1:296 char:5
    + $mail.SendAndSaveCopy()
    + ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServiceRequestException

    1. Dave

      I’m also getting the error. How did you verify the role is assigned?

    2. Paul Cunningham

      I’ve seen this with certificate issues. Even after replacing the self-signed cert with one from an internal CA I sometimes still run into the problem when trying to run the Start-MailGen.ps1 script directly on the Exchange server. Usually it works fine if I do it from a non-Exchange server that has just the management tools installed.

      1. Dixon

        I tried to run this from a server not in the Exchange environment, but the error still persists. Any other ideas?

  38. Justin

    Paul, this is awesome. Do you know if there is a way to set PermissionControlled through EWS Managed API? I have looked around without much luck, but I was hoping to introduce some protected content into the test also to see how the Journal Decryption agent affects performance.

    1. Paul Cunningham

      No idea to be honest. The EWS API is pretty well documented on MSDN or I would suggest posting in the Exchange Developers forum on TechNet or checking Glen Scale’s blog to see if he has any tips for that.

  39. Aorta

    Hi Paul,

    I am trying to run the script in an Exchange 2013 environment from a Win 7 machine running PS 3.0 and all the prerequisites you mentioned in the blog but I get the following errors :

    Exception calling “SendAndSaveCopy” with “0” argument(s): “The Id property must be set.”
    At C:Userssa-exc-impDesktopStart-MailGen1Start-MailGen.ps1:296 char:26
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    *** New email message
    Cannot process argument transformation on parameter 'Identity'. Cannot convert value "TA_Alain Struillou" to type "Micr
    osoft.Exchange.Configuration.Tasks.MailboxIdParameter". Error: "Cannot convert hashtable to an object of the following
    type: Microsoft.Exchange.Configuration.Tasks.MailboxIdParameter. Hashtable-to-Object conversion is not supported in res
    tricted language mode or a Data section."
    + CategoryInfo : InvalidData: (:) [Get-Mailbox], ParameterBindin…mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-Mailbox

    You cannot call a method on a null-valued expression.
    At C:Userssa-exc-impDesktopStart-MailGen1Start-MailGen.ps1:232 char:31
    + if($SenderSmtpAddress.GetType <<<< ().fullname -eq "Microsoft.Exchange.Data.SmtpAddress") {
    + CategoryInfo : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Sender:
    Subject: Stygian adamant ossify
    Cannot process argument transformation on parameter 'Identity'. Cannot convert value "Astruill Microsoft" to type "Micr
    osoft.Exchange.Configuration.Tasks.RecipientIdParameter". Error: "Cannot convert hashtable to an object of the followin
    g type: Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter. Hashtable-to-Object conversion is not supported in
    restricted language mode or a Data section."
    + CategoryInfo : InvalidData: (:) [Get-Recipient], ParameterBindin…mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-Recipient

    You cannot call a method on a null-valued expression.
    At C:Userssa-exc-impDesktopStart-MailGen1Start-MailGen.ps1:272 char:38
    + if($RecipientSmtpAddress.GetType <<<< ().fullname -eq "Microsoft.Exchange.Data.SmtpAddress") {
    + CategoryInfo : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Recipient:
    Exception calling "Add" with "1" argument(s): "Object reference not set to an instance of an object."
    At C:Userssa-exc-impDesktopStart-MailGen1Start-MailGen.ps1:282 char:35
    + [Void] $mail.ToRecipients.Add <<<< ($EmailRecipient)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Cannot process argument transformation on parameter 'Identity'. Cannot convert value "sa-exc-imp" to type "Microsoft.Ex
    change.Configuration.Tasks.RecipientIdParameter". Error: "Cannot convert hashtable to an object of the following type:
    Microsoft.Exchange.Configuration.Tasks.RecipientIdParameter. Hashtable-to-Object conversion is not supported in restric
    ted language mode or a Data section."
    + CategoryInfo : InvalidData: (:) [Get-Recipient], ParameterBindin…mationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-Recipient

    You cannot call a method on a null-valued expression.
    At C:Userssa-exc-impDesktopStart-MailGen1Start-MailGen.ps1:272 char:38
    + if($RecipientSmtpAddress.GetType <<<< ().fullname -eq "Microsoft.Exchange.Data.SmtpAddress") {
    + CategoryInfo : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

    Do you have an idea why this might happen ?

    Thanks

    1. Paul Cunningham

      Have you modified the script in any way?

      Have you tried hard coding the EWS URL?

      1. Aorta

        Hi Paul,

        Thanks for replying to my post 🙂

        I finally managed to solve the issue by installing the Exchange 2010 Management Tools on the workstation and hardcoding the EWS to an Exchange 2010 server.

        In fact the first time i did modify the script in order to import the PSSnapin for Exchange 2013 as this would fail with unable to load any snapin… I think this was causing the issue…

        Thanks for a great script Paul and i hope this will help others running into the same issue.

  40. Jonathon

    Script also does not work in a 2007/2010 mixed environment

  41. Jonathon

    The new script is not available for download

    1. Paul Cunningham

      Sorry about that. Download system broke recently. I’ve replaced the link with a working one now.

  42. sm00th

    Hi,

    First of all, this is a kickbutt script! Thank you so much.

    Now, my question is, is there a way to SPECIFY the email recipients? Not just random? Here’s the thing, I need to stress test my Exch 2010 servers in PROD. A little backstory first, I’m in the middle of migrating from Exch 2007 to Exch 2010. Right now both Exchange 2007 and 2010 are coexisting but I have not cutover yet. Everything flows to Exch 2007 first, then if the email is intended for an Exch 2010 mailbox then it send it to the Exch 2010 mailbox.
    Before I actually move all users from 2007 to 2010, I need to make sure my Exch 2010 Mailbox servers can handle the load (it’s a physical server with local attached disks).

    If I run this script, it’s going start spamming random Exch 2007 users, and I don’t want that… well, at least I don’t want to be here when that happens 🙂

    Any help is greatly appreciated.

    Thanks again!

    1. Paul Cunningham

      I don’t recommend using this script in any production environment (or any script like it for that matter). It is not intended to be used to validate a hardware/storage design.

      If you’ve sized your server and storage hardware based on the Exchange 2013 sizing calculator that Microsoft published, and you want to validate that, then Microsoft also has tools such as Jetstress for that task.

  43. Jerry

    First, this is AWESOME for labs. Just fantastic. I’m so happy I don’t have to run LoadGen 24×7 🙂

    A little about my experience:
    I created a whole new account to do this with in the lab. On the first run, it only found one recipient, which took me a while to realize, it only found it’s own mailbox. Get-mailbox only returned itself! Woops!

    I added the account I use “SMTP Test” to the Exchange Recipient Management RBAC Group. Which solved the problem! Now it’s just chugging away.

  44. Itworkedinthelab

    Great help
    Thanks a lot
    highly appreciated

  45. Dave

    Paul,

    Great script, I’m using it pretty much out of the box on Exchange 2013 CU3 on Windows 2012 and EWS API 2.0 (changed the path in the script to point to the proper DLL)

    One thing I did notice was that the last mailbox (user name of Zena), never sent or received email. Basically it was part of this line in your script:

    $rand = Get-Random -Minimum 0 -Maximum ($mailboxcount – 1)

    If you look at the TechNet article for the Get-Random command (http://technet.microsoft.com/en-us/library/ff730929.aspx), it states that the maximum must be 1 more than your desired maximum:

    “And yes, -maximum must always be set to 1 more than the high number in the range. That means that, to select a random number between 1 and 100, we must set –maximum to 101; if we set –maximum to 100 then we’d actually select a random number between 1 and 99. ”

    By subtracting 1 from $mailboxcount, the last mailbox would never be used. I changed the line and removed the -1 and the last mailbox is now sending and receiving email.

    Thanks again, this is fantastic. I’m busy loading up my mailboxes across six databases to test auto reseed 🙂

  46. Brian

    Hey all,

    Can’t wait to work with this script, however I receiving the following error when I try to run the script.

    I have EWS Managed Api 1.2 installed. Exchange 2010 SP3

    Exception calling “SendAndSaveCopy” with “0” argument(s): “The request failed. The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”
    At C:Usersbashipman-admDesktopMailgenStart-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Thanks,
    Brian

    1. Brian

      Fixed that issue…

      http://blogs.technet.com/b/sbs/archive/2007/04/10/installing-a-self-signed-certificate-as-a-trusted-root-ca-in-windows-vista.aspx

      Now running into:

      Exception calling “SendAndSaveCopy” with “0” argument(s): “An element node ‘soap:Envelope’ of the type Element was expected, but node ‘Autodiscover’ of type Element was found.”
      At C:Usersbashipman-admDesktopMailgenStart-MailGen.ps1:186 char:23
      + $mail.SendAndSaveCopy <<<< ()
      + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : DotNetMethodException

      1. Brian

        Tried to fix the issue by disabling all authentication methods on the Autodsicover virtual directory except Basic and received.

        Exception calling “SendAndSaveCopy” with “0” argument(s): “The request failed. The remote server returned an error: (401) Unauthorized.”
        At C:Usersbashipman-admDesktopMailgenStart-MailGen.ps1:186 char:23
        + $mail.SendAndSaveCopy <<<< ()
        + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException

        Then I tried just Windows Authentication (Disabled Basic and Anonymous) and received:

        Exception calling "SendAndSaveCopy" with "0" argument(s): "The response received from the service didn't contain validXML."
        At C:Usersbashipman-admDesktopMailgenStart-MailGen.ps1:186 char:23
        + $mail.SendAndSaveCopy <<<< ()
        + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException

        1. vishwanath

          Hi,

          the user running the power shell should be mailbox enabled and should have full access to all mailbox.
          Unless the user does not have full access to mailbox it fails to save the copy
          the user should have impersonationAssignmentName role assigned
          under #Web services initialization
          you need to set the $service.URL to https://casserver /ews/exchange.asmx

  47. Dan

    Paul,

    Great script as I got it to run in my Exch 2007 test environment. Is there a way to get this script to run continuously and not wait for the next hour? Additionally, I think I know how to increase the amount of emails generated but want your input….What I’m testing in Dev is to generate many tracking logs for our Arcsite environment.

    Thanks,

    Dan

  48. Eugene

    Hi

    Had the same error for “Exception calling “SendAndSaveCopy” with “0″ arguments(s): “Exchange Server doesn’t support the requested version.””.

    Ran Exchange 2010 SP3 on Server 2012. Installed API version 2.0.

    Changed the following in the script and errors was gone.

    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService(“Exchange2010_SP2″)

    Tried SP2 although it was SP3 and it worked.

  49. Jarrett

    Hi Paul,

    I was looking for something like this for testing. Looks exactly like what I need in my test environment. I currently have Exchange 2010 SP1 running on Windows 2008 R2 server. I have the ” Exchange Web Services Managed API 2.0″ installed on the Exchange Server and the script is pointing to the dll “$dllfolderpath = “C:Program FilesMicrosoftExchangeWeb Services2.0Microsoft.Exchange.WebServices.dll””

    When I run the script I’m getting the following error each time it attempts to send an email from a user to a user:

    Exception calling “SendAndSaveCopy” with “0” arguments(s): “Exchange Server doesn’t support the requested version.”
    At c:generate emailstest email generatorStart-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    +CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    +FullyQualifiedErrorID : DotNetMethodException

    I did try pointing directly to the EWS address instead of using the Autodiscover but I continue to get the error message.

    The problem seems to be on line 186 of the code "$mail.SendAndSaveCopy()". If I comment this out the script does seem to run successfully but no emails are actually sent. It just appears to go through the motion of sending emails.

    Any help you can give would be greatly appreciated.

    Thanks!

    1. Paul Cunningham

      I ran into this issue myself and I can’t remember what exactly was the the cause. I think it was the version of the EWS API needing to be an earlier one (1.x would probably work fine with Exchange 2010 SP1).

      So you could try some of the older API versions, or upgrade the Exchange server to 2010 SP3 which should work with API version 2.0 AFAIK.

      1. Jarrett

        I was actually able to get it working by adding the Exchange Version to the following line in the code:
        $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService(“Exchange2010_SP1″)

        I found this in the subscriber comments above.

        There is another tech in my office who is having some issues as well but we believe its related to his test exchange server and impersonation rights. He’s rebuilding that server and we hope to get it up and running on his by next week.

        Thank you for your help!

  50. Jon

    Hey Paul,

    great script, is there a way I could slow the email generation down?

    Having issue when sending large volumes, some of the emails don’t get sent and end up in draft folder of the accounts.

    Cheers

    1. Paul Cunningham

      Sure. Look at the loop where the actual emails are being sent, and just add a Start-Sleep for as long as you need after each email is sent.

  51. Paulo

    Thank you very much for this amazing help.

    Lab up and running

    Regards

  52. Pat

    Is there any way to find if the attached file is of certain type like xls, jpg, docx, etc, without just looking at the file extension, but by looking at the content-type using ews managed api?

  53. DamianGarbus

    It’s Great 🙂 I had a problem but now it’s works. Thanks 🙂

  54. Shakti

    Is attachment thing possible??

    1. Vishwanath

      Yes You can send attachment

      Add the line under

      $mail.From = $EmailSender
      $mail.Attachments.AddFileAttachment(“full path of the file to be attached”)

      Example
      $mail.From = $EmailSender
      $mail.Attachments.AddFileAttachment(“C:UserstestexchangeDesktopemailu_ex110430.zip”)

      save the file and run you should be able to send attachment

      1. Shakti

        Thx Vishwanath, will try that out!

      2. Shakti

        one more thing, your suggestion hard codes the attachment file.
        Is there a way the script randomly picks from the set of files from a given folder.
        Say randomly pick any file from the directory C:Attach.

        1. Dave

          Shakti,

          You could do a lookup to put the list of filenames in the directory into an array and then do a Get-Random against that array to select the attachment for a particular email. If you wanted to get even fancier, you could always do another random true or false to see if a particular email actually gets an attachment or not.

          Cheers

        2. Sam O'Donnell

          Shakti,

          I followed Vishwanath’s advise about the “$mail.Attachments.AddFileAttachment(“C:UserstestexchangeDesktopemailu_ex110430.zip”)”

          however I changed it a little!

          I added two new lines to the script,
          $attach = Get-childitem C:scriptsmailgenattachments*.* | Get-Random -Count 1
          obviously change the folder as to where you want to store the attachments, I just have a few pdf. img, mp3, docx files in there.

          above this existing line in the script
          $mail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)

          and then I added this line
          $mail.Attachments.AddFileAttachment(“$attach”)

          so my script now looks like this

          $attach = Get-childitem C:scriptsmailgenattachments*.* | Get-Random -Count 1
          $mail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)
          $mail.Subject = $emailSubject
          $mail.Body = $emailBody
          $mail.From = $EmailSender
          $mail.Attachments.AddFileAttachment(“$attach”)
          [Void] $mail.ToRecipients.Add($EmailRecipient)
          $mail.SendAndSaveCopy()

          Now obviously this will then send attachments to every email it sends, so all have done is modify the number of sending emails, and run the original script to. so I get both lots of emails with and without attachments delivered within the test lab.

          hope that makes sense!

          Sam

  55. Shakti

    Using this script with slight modification, Is there a way to add attachments from a given set of attachment types (.txt, .doc, .img etc)???

    1. Paul Cunningham

      I’m sure its possible I just haven’t looked into it. It would be handy though, I might try and include it in the next version.

  56. Shakti

    Amazing work buddy!
    Just add impersonation part to the prerequisite in the script itself, rest is awsome!
    Cheers!!!!

  57. Manu Philip

    Hi Paul,

    This is an excellent contribution. May I ask some customization. I need a similar script to test my exchange online. The script should send repeated email to some particular internal email ids (from a csv). with a 5 minutes delay. Then we need to get the analyzing done on how was the delay in each send. Can you help?

    Thanks,
    Manu

  58. Brian Flanagan

    Has anyone tried this script with Exchange 2013? I need to do some load testing with Exchange 2013 and I’m trying to find tools other than loadsim. This tool works great on Exchange 2010!

    Thanks

    1. Sam O'Donnell

      yes! and it works.. well i had to tweak some things..

      i did all of the above, but i was seeing some SendAndSaveAs issues.

      i hashed # out

      #$mail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)
      #$mail.Subject = $emailSubject
      #$mail.Body = $emailBody
      #$mail.From = $EmailSender
      #[Void] $mail.ToRecipients.Add($EmailRecipient)
      #$mail.SendAndSaveCopy()

      and added this directly underneath

      Send-MailMessage -SmtpServer FRONTENDCAS -From $emailsender -To $EmailRecipient -Subject $emailSubject -Body $emailBody

      it was a long shot but it works..

      Paul, hope you don’t mind 🙂

      1. Paul Cunningham

        That will work but its just sending with SMTP so it doesn’t save the item to the sender’s Sent Items, isn’t as useful for generating test traffic for message tracking etc, doesn’t necessarily use multiple HT’s if available, etc etc. Depends whether you need all that or just the ability to send a bunch of raw traffic around.

        1. Chad

          Paul – do you have a suggestion for how to make this work correctly on Exchange 2013? I did make the changes that Sam suggested and that’s working, but I’d like items to be logged in the sent items if possible. Thanks!

        2. Paul Cunningham

          I imagine for Exchange 2013 it will be a simple case of using the latest EWS API DLL and updating the script variable that points to the DLL path. But I haven’t had a chance to test that yet.

        3. Chad

          I did get this to work on 2013. I had quite a few issues and saw lots of different errors (most of the ones talked about above and a few more) but they were all issues with my lab…mostly caused by a DNS issue on my DC. After resolving those and undoing all the hacks I was doing to the script trying to get it to work, it works like a champ.

          To get it to work after other issues were resolved, I just had to update the path to the EWS DLL that’s included in 2013 and it does work as expected. Thanks for this awesome script, it’s going to make my 2013 eDiscovery testing much easier.

        4. Paul Cunningham

          Great, thanks for letting us know. And yes, eDiscovery testing is exactly the type of thing this script is designed to create realistic looking traffic for, so that is awesome 🙂

  59. Jason Williams

    Do you think it would be possible to run this against at test environment on Microsoft Live@edu?

  60. Russ Dillion

    Thanks for the tip Paul! I installed SP2 on my test server and the script is now running great!

  61. Geoff

    Hi Paul,
    Well I got the script working and ran it for a bit but let it set for a few weeks and now when I try and run the script I get the following error,
    Get-Random : Minimum (0) cannot be greater than or equal to Maximum (-1).
    At C:scriptsmailgenStart-MailGen.ps1:148 char:20
    + $rand = Get-Random <<<< -Minimum 0 -Maximum ($mailboxcount – 1)
    + CategoryInfo : InvalidArgument: (:) [Get-Random], ArgumentException
    + FullyQualifiedErrorId : MinGreaterThanOrEqualMax,Microsoft.PowerShell.Commands.GetRandomCommand

    Thanks
    Geoff

    1. Paul Cunningham

      I would say $mailboxcount is returning 0 for some reason. I assume you’ve still got mailbox users in your test lab?

      1. Geoff

        Hi Paul
        Yes I still have mailboxes configured in my test environment
        thanks
        Geoff

        1. Geoff

          Well Paul, I found my problem. I discovered that I was using the wrong power shell, what a bonehead mistake. its been a long week.
          However I get this new error
          [PS] C:scriptsmailgen>.Start-MailGen.ps1
          Retrieving mailbox list
          Preparing EWS
          Starting email generation
          *** Will send 692 emails this hour
          Exception calling “SendAndSaveCopy” with “0” argument(s): “The request failed. The underlying connection was closed: An unexpected error occurred on a sen
          d.”
          At C:scriptsmailgenStart-MailGen.ps1:186 char:23
          + $mail.SendAndSaveCopy <<<< ()
          + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
          + FullyQualifiedErrorId : DotNetMethodException

          Any ideas where I might find why it is getting a send error?
          thanks
          Geoff

        2. Paul Cunningham

          Something interrupting the SMTP connection to the Transport server you’ve configured in the script variables?

          If you test it with Telnet does it work?

        3. Geoff

          Hi Paul
          That is what it appeared to me as well but I can telnet into port 25 and it responds back fine
          Thanks
          Geoff

  62. Sam

    Paul!

    is there a way this script can be modified to target mail enabled public folders? i am trying to prove a point for a customer who has 1000+ public folders and they want to upgrade to 2010!

    1. Paul Cunningham

      *** I’ll repeat the warning not to use this script in production environments. ***

      On line 236 is the code that determines the mailboxes that are used by the script. You could probably modify that to get mail-enabled public folders instead.

      1. Sam

        its in a demo environment that is no where near the live environment!

        i have tried that but get a long list of errors! it does however pick up the names of the public folders..

        “cannot process argument transformation on parameter ‘Identity’. Cannot convert the “PUBLICFOLDERNAME” value of type “Microsoft.Exchange.Data.Directory.Management.MailPublicFolder” to type “Microsoft.Exchange.Configureation.Tasks.MailboxIdParameter”

        any ideas?

  63. Mike

    Hey Paul,

    I executed the following command first and still get the error below. Any idea? By the way, I am using Exchange Web Services Managed API 1.1

    [PS] C:\>New-ManagementRoleAssignment -Name:impersonationAssignmentName -Role:ApplicationImpersonation -User:administrator

    Exception calling “SendAndSaveCopy” with “0” argument(s): “The account does not have permission to impersonate the requested user.”
    At C:ScriptsMailgenStart-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    1. Paul Cunningham

      After granting impersonation rights you’ll need to start a new shell session for it to take effect.

      1. Mike

        Perfect! That was it. Thanks so much. Its a great script! Any idea when this script will work with Exchange Web Services Managed API 1.2?

        1. Paul Cunningham

          If you’re running Exchange 2010 SP2 I think it actually does work fine with the EWS v1.2, you just need to update this variable in the script with the correct path: $dllfolderpath

  64. Russ Dillion

    Paul,

    First, thank you very much for your time and efforts on this. I have been trying to get this working in a test environment for a couple of days now, and am running into an error that I have not been able to solve. I have a 2008 R2 DC, and a 2008 R2 mail server with Exchange 2010 SP1. I believe I have autodiscover configured correctly, and am using the self signed certificate from the Excahnge server. I have added it to the Trusted Root CA store on the server as well. I installed Exchange Web Services Management API version 1.2 as I could not find version 1.1. When I run the script, I am getting the following:

    Retrieving mailbox list
    Preparing EWS
    Starting email generation
    *** Will send 867 emails this hour
    Exception calling “SendAndSaveCopy” with “0” argument(s): “Exchange Server doesn’t support the requested version.”
    At C:scriptsStart-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Any ideas?

    Thanks again,

    Russ

      1. Eric

        Does anyone know where I can get a copy of API v1.1? Everywhere i’m looking all I can find is 1.2 or higher. I’ve almost got Exchange 2007 to work but now i’m receiving the same error “Exchange Server doesn’t support the requested version.” I believe with API v1.1 I will have it functioning correctly and will post the changes that were needed in order to make it work.

      2. Vikram

        Hi Paul,

        I am using exchange & outlook 2010, trying to move messages from inbox to Temp folder in the same mailbox.. but I am getting the following error message at line below..

        $Mailbox = “name@domain.com”
        $service.AutodiscoverUrl($Mailbox, {$True}); – This throws an error message..

        Exception calling “AutodiscoverUrl” with “2” argument(s): “The Autodiscover service could not be located.”
        At C:adMoveItems.ps1:244 char:27
        + $service.AutodiscoverUrl <<<< ($Mailbox, {$True});
        + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : DotNetMethodException

        Please let me to solve this issue.. I am new in dealing with exchange mailboxes.

        Regards,
        Vikram

  65. Eric

    I’ve made significant progress in getting this script to run in my lab environment. However, I’m now receiving the following error.

    I’m running Exchange 2007 with a Windows 2008R2 DC in the environment. I have worked through several other issues but unable to resolve this one.

    Any assistance would be great appreciated!

    [PS] D:scriptsmailgen>D:ScriptsMailgenStart-MailGen.ps1
    Retrieving mailbox list
    Preparing EWS
    Starting email generation
    *** Will send 822 emails this hour
    Exception calling “SendAndSaveCopy” with “0” argument(s): “An element node ‘soa
    p:Envelope’ of the type Element was expected, but node ‘Autodiscover’ of type E
    lement was found.”
    At D:ScriptsMailgenStart-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    1. Paul Cunningham

      Hi Eric, I’ve done no testing against Exchange 2007 with this script. I only use it in Exchange 2010 test lab environments.

      1. Eric

        Paul,

        Thanks for the update. I am one step closer to making this work. The problem that was listed above was because I was pointing to the Autodiscover.xml file and it was looking for the ews/exchange.asmx file. Once I pointed that correctly then it is now giving me the error “Exchange Server doesn’t support the requested version.” and I believe that is because I’m running API v1.2 instead of v1.1. Any assistance on finding or obtaining a copy of v1.1 would be greatly appreciated.

        Eric

        1. Phil

          Eric- did you remember to enable impersonation for the user you are running the script as?

          foreach ($exchangeServer in Get-ExchangeServer)
          {
          if ($exchangeServer.ServerRole -match ‘ClientAccess’)
          {
          Add-ADPermission -Identity $exchangeServer.DistinguishedName -User ‘domainuser’ -ExtendedRights ms-Exch-EPI-Impersonation
          }

          }

          Fixed my headache with exchange 2007 and this script. so far, removing SSL (for a throw away lab, disabling SSL was far simpler), commenting out the exchange.2010 tools, hard coding the services url, and finally giving impersonation permissions to my script user got it all working.

          Great script Paul, thank you very much!

  66. Gary

    Thanks Steve.

    It was that simple!

    Must make note to self to get head round powershell.

    Thanks again.

    regards
    Gary

    1. Gary

      Thanks Paul. (no idea why I typed Steve !, to much Red wine)

      It was that simple!

      Must make note to self to get head round powershell.

      Thanks again.

      regards
      Gary

  67. Gary

    Nice script, very useful.. Thank you for your time spent.

    I’ve been trying to modify the sender to be able to exclude certain addresses, without much sucess. Any pointers would be appricated.

    Regards
    Gary

    1. Paul Cunningham

      This line in the script fetches the list of mailboxes to include.

      $mailboxes = @(Get-Mailbox -RecipientTypeDetails UserMailbox -resultsize unlimited)

      So you can just modify that Get-Mailbox any way you like to exclude the ones you don’t want. Help info for Get-Mailbox is here:
      http://technet.microsoft.com/en-us/library/bb123685.aspx

      One way would be to use the -OrganizationalUnit parameter to just get the users in a specific OU, and have the ones you want to exclude be outside of that OU.

  68. Jan

    Paul this is so cool, i can’t thank you enough for this article en the scripts to put a mail load on a
    lab test environment.

    Very …..very much appriciated was looking for this for quite some time

  69. Geoff

    Hi Paul
    I am getting the same error message but I am unsure how to hard code the URL can you help me out?
    Exception calling “AutodiscoverUrl” with “1″ argument(s): “The Autodiscover service couldn’t be located.”
    At C:ScriptsMailgenStart-MailGen.ps1:245 char:25
    + $service.AutodiscoverUrl <<<< ($user.Properties.mail)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Thanks
    Geoff

    1. Paul Cunningham

      Hi Geoff (and others),

      Firstly I would double-check that Autodiscover is working at all in your test lab. If there is anything wrong with it, or your SSL cert, then try fixing that first.

      Other than that, I am planning to update the script for compatibility with the EWS API v1.2, so I will look to include the manually specified Autodiscover URL option in the next version. Hopefully not far away.

    2. Paul Cunningham

      Actually I’ve just added a note to the end of the article with the required script edits to hard-code the URL, if you’re looking for a quick win.

      1. Geoff

        Thanks Paul that helped that problem but now I am having to find out why I am having a permissions/trust Exception calling “SendAndSaveCopy” with “0” argument(s): “Request failed. The underlying connection was closed: Could not establish trust relationship fo
        r the SSL/TLS secure channel.”

        Some times this stuff makes me pull my hair out.

        Thanks again for your help
        Geoff

      2. Paul Cunningham

        Geoff, that sounds like a certificate issue to me. The same issue is probably why Autodiscover isn’t working in the first place.

        1. JRyen

          How does one solve this issue?

          1. Robert

            Hi Paul,

            I have almost the same error but :

            “Exception calling “SendAndSaveCopy” with “0” argument(s): “Request failed. The underlying connection was closed: An unexpected error occured on a send”

            I’m in an Exchange 2016 environment, can this explain this error which is not very clear?

            Thanks 🙂
            Robert

        2. JRyen

          Thanks Paul,

          I was able to follow your article and others of your articles about SSL for exchange. Once set up a CA and made a signed cert, then it all worked great. Thanks for making good scripts and such easy and excellent articles. They’re detailed and easy to read. Thanks. Keep up the good work 🙂

  70. Heikal

    I successfully solved that error ,I used EWSManaged API version 1.1 instead of 1.2 and your script works fine …the old version (1.1) was not found on Microsoft download center anymore..But got it from “Mike Pfeiffer” Blog “http://www.mikepfeiffer.net/downloads/ExchangeLab.zip” under “bin” folder

    1. Paul Cunningham

      I’ll try and update the script for v1.2 if the 1.1 is going to be unavailable for people :-/

  71. Heikal

    Hi Paul ,

    Create Efforts

    but I got the following error

    Exception calling “SendAndSaveCopy” with “0″ argument(s): “The mailbox that was requested doesn’t support the specified RequestServerVersion.”

    knowing that version of EWSManged API is 1.2

  72. J

    This is awesome. Thanks for the work.

    I will be using this (probably frequently) and provide any feedback and suggestions I have. One quick question… do you know what is this script does not work in Ex 2007? I would ideally like something that works for either version of Exchange… but will look into it myself.

    THanks for your work and for sharing it with the world.

    J

  73. Andrew

    Hello Paul –
    What could be causing this;

    Exception calling “SendAndSaveCopy” with “0” argument(s): “The mailbox that was requested doesn’t support the specified
    RequestServerVersion.”
    At C:ScriptsMailGenStart-MailGen.ps1:186 char:23
    + $mail.SendAndSaveCopy <<<< ()
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    1. Lucas

      I had the same problem and explicitly specifying version of exchange server fixed it:
      $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService(“Exchange2010_SP1”)

      Other possible values:
      http://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.exchangeversion%28v=exchg.80%29.aspx
      Where I found out about this argument:
      “Note that the EWS Managed API 1.1 defaults to Exchange2010_SP1 as the Exchange version that it is connecting to. If you are running another version of Exchange or another service pack, you must specify the correct version by passing the ArgumentList parameter to New-Object.”
      http://blogs.technet.com/b/heyscriptingguy/archive/2011/12/02/learn-to-use-the-exchange-web-services-with-powershell.aspx

  74. Simon

    Hi Paul,

    I’m getting the same error as above and the account does have a mailbox.

    1. Paul Cunningham

      You could try hard coding the Autodiscover URL instead of the script trying to discover it.

      1. Stephane Favre

        Please share how you would hardcode the Autodiscover URL into your script.

  75. Raj

    I am getting this error.
    [PS] C:ScriptsMailgen>.Start-MailGen.ps1
    Retrieving mailbox list
    Preparing EWS
    Exception calling “AutodiscoverUrl” with “1” argument(s): “The Autodiscover service couldn’t be located.”
    At C:ScriptsMailgenStart-MailGen.ps1:245 char:25
    + $service.AutodiscoverUrl <<<< ($user.Properties.mail)
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

    Running Exchange on DC with Win 2008 R2.

    1. Paul Cunningham

      Does the account that you’re using to run the script have a mailbox?

      1. Raj

        Sorry for the delay
        Iam using administrator account and having mailbox.

      2. Raj

        Hi paul,

        It is working fine.
        Thank You for your script.

        Raj

  76. Ifiok

    Paul,
    Great script – I have been looking for something like this. I have been using this script for the past 2 days and I’m very impressed by the amount of work you put in to generate the script.

    My only comment is this: How about using a text file to log all that information that we “write-host” – For two reasons :
    a) we can review later if we need to, especially if there are errors – this one just scrolls by and we cannot see it anymore.
    b) aslo it frees up screen and runs at the background.
    Just my thoughts.
    Thanks for the sharing it with us.

    1. Paul Cunningham

      Seems like a good idea. I’ll try to include that in the next version.

  77. kottees

    Thanks for the reply. Sure I will try tonight and let you know the result.

  78. kottees

    Hollo Paul,

    This is the error I’m getting while running.. DC on win 2k3 server and Exch 2010 typical roles installed on win 2008 R2. I could not find the solution for this over the internet.. Please suggest me.
    ************************************************************
    [PS] C:Paul>.Start-MailGen.ps1
    WARNING: Error initializing default drive: ‘Unable to find a default server with Avtive Directory Web Services running.’.
    Retrieving mailbox list
    Preparing EWS
    Exception calling “AutodiscoverUrl” with “1” argument(s): “The Autodiscover service couldn’t be located.”
    At C:PaulStart-MailGen.ps1:245 char”25
    + $service.AutodiscoverUrl <<<< ($user.Properties.mail)
    +CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    +FullQualifiedErrorId : DotNetMethodException

    Starting email generation
    *** Will send 615 emails this hour
    Exception calling "SendAndSaveCopy" with "0" argument(s): "The Url property on the ExchangeService object must be set."
    At C:PaulStart-MailGen.ps1:245 char"23
    + $mail.SendAndSaveCpy <<<< ()
    +CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    +FullQualifiedErrorId : DotNetMethodException
    *********************************************************

      1. Shakti

        Paul,
        I was getting error when i ran the script on Exchaneg 2013 (CAS + Mailbox) server.
        “Could not establish trust relationship for the SSL/TLS secure channel.”

        Then I installed the certificate but now getting the error

        “The Url property on the ExchangeService object must be set….”
        My server is 2012 R2 hence I don’t have to install “Active Directory Management Gateway Service” as suggested by you above and its not letting me run that update.

        What should I do??

        1. Paul Cunningham

          Try hard-coding the EWS URL as demonstrated at the end of the article.

  79. Tom

    Hi Paul,
    Thanks for the info. I will be setting up my test lab this weekend and I will let you know how it goes.

    Cheers.
    TP

  80. kottees

    Thank you so much Paul, I was looking for something like this. Will tell you once tried in my lab.

  81. Ariel

    Great article Paul! It will be very helpfull for my labs. Thanks you.-

  82. Sam

    Love this! will help so much in terms of testing and developing.

Leave a Reply