Sending an attachment via powershell is timing out

Posted on 2011-10-12
Last Modified: 2013-08-02
I have a powershell script to look in a folder for existence of a file, and email it to an address as follows:

(Note: I have inserted the xxx's for addresses and server, the script has real details here)

#Path to driver sheets folder
$checkForFiles = "c:\predict\sheets\*"
#Test for the existence of files
$fileExistence = test-path $checkForFiles

#check for the existence of files in the C:\Predict\Sheets folder
            if ($fileExistence -eq $true)
            # If files exist send them as attachments
            send-mailmessage -subject "Run Sheets" -from depot@xxx.xx -to predict@xxx.xx -smtpserver xxxxx -attachments (get-childitem $checkForFiles)
        sleep 5
        Move-Item (get-childitem $checkForFiles) C:\predict\archive -force
      # If no files exist, do nothing
      {write-host "nothing to process"}

I have this running via a scheduled task in 37 locations, but it is failing in just one place.

The error is:

Send-MailMessage : The operation has timed out.
At C:\Predict\email-runsheets.ps1:11 char:19
+         send-mailmessage <<<<  -subject "Run Sheets" -from depot@xxx.xx -to predict@xxx.xx -smtpserver xxxx -attachments (get-childitem $checkForFiles)
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [
   Send-MailMessage], SmtpException
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

I do not get this error with a very small attachments, (less than 1mb), but I am getting it with a 1.8Mb
It appears that the session is timing out before it gets to complete sending the mail.

I see scripts on the internet that allow you to put a timeout in place for exactly this purpose (e.g.  but I would like to use my
script as it works in 37 different places except this one, and I want it to be standard script.

Is there some cmdlet in powershell 2 that I can add to the script to keep the mail session "alive" until
it is complete, or can anyone suggest a suitable fix?  

Thank you.
Question by:Interlink_IT
    LVL 5

    Expert Comment

    can you try changing this:

                send-mailmessage -subject "Run Sheets" -from depot@xxx.xx -to predict@xxx.xx -smtpserver xxxxx -attachments (get-childitem $checkForFiles)

    to this:
    get-childitem $checkForFiles | foreach{$_.fullName} | send-mailmessage -subject "Run Sheets" -from depot@xxx.xx -to predict@xxx.xx -smtpserver xxxxx

    Author Comment

    Thanks for replying, but that gives the same timeout error message when I try and send a 1.8mb file.


    Author Comment

    Is there a cmdlet that could zip up the file before attaching it maybe?  If this got the size down, then the emailing will probably work.

    LVL 5

    Expert Comment

    For zipping you may want to check out the PowerShell community extentions....

    there is a cmdlet called 'write-zip'.  I haven't had a need to use it for myself, but I believe you need to install 7-zip for it all to work.
    LVL 8

    Expert Comment

    Have you considered testing for the size of the file and then if it is over 1Mg, using a different timeout?

    As an aside,  if ($fileExistence -eq $true)  should work as  if ($fileExistence), which ,IMO, is a bit cleaner.


    Author Comment

    @bchallis: The problem is that I can't set a timeout anywhere, unless you can advise on how?

    LVL 8

    Accepted Solution

    The cmdlet provided by PowerShell 2.0 does not seem to provide a hook in to the TimeOut parameter so it may be necessary to drop back to the underlying Framework classes.  Here is a sample of some code that I was using in PowerShell 1.0 to send an attachment, I have added in a test for the attachment size to modify the timeout if necessary:

    Write-Host "Preparing to send email"
    $from = New-Object System.Net.Mail.MailAddress ""
    $to =   New-Object System.Net.Mail.MailAddress ""
     $scheduleFileName = "file path and name"

    # Create Message
    $message = New-Object  System.Net.Mail.MailMessage $from, $to
    $message.Subject = "Subject"
    $message.Body = "Email Body"

    # Create the attachment
    [Net.Mail.Attachment]$att = New-Object Net.Mail.Attachment($scheduleFileName, "text/plain")

    # Set SMTP Server and create SMTP Client
    $server = ""
    []$client = New-Object $server
    $client.Port = 587
    $client.EnableSsl = $true
    $client.Credentials = [Net.NetworkCredential](Get-Credential "brent.challis")
    if ((Get-Item $scheduleFileName).Length -gt 1000000)
          $client.Timeout = 100
    # Send the message
    "Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port
    try {
       "Message to: {0}, from: {1} has beens successfully sent" -f $to, $from
       Add-Content $logFileName ("Sent Schedule: " +(Get-Date))
    catch {
      "Exception caught in CreateTestMessage: {0}" -f $Error.ToString()

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Hi all.   The other day I had to change the passwords for a bunch of users on the fly. Because they were so many, I decided to do it in an automated way and I would like to share it with you all.   If you are not doing it directly in a Domain Co…
    This script checks a path to see if a folder exists. If the folder does exist you will get output "The folder has previously been created. No action taken" If not it will create the folder. Then adds one user modify permission to the folder. It …
    Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
    Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

    760 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    13 Experts available now in Live!

    Get 1:1 Help Now