?
Solved

Sending an attachment via powershell is timing out

Posted on 2011-10-12
9
Medium Priority
?
2,026 Views
Last Modified: 2013-08-02
Hi,
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
      else
      {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
file.
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. http://mspowershell.blogspot.com/2007/12/send-smtpmail-update.html)  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.
Dermot.
0
Comment
Question by:Interlink_IT
  • 3
  • 2
  • 2
7 Comments
 
LVL 5

Expert Comment

by:daveTechSearch
ID: 36963970
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
0
 

Author Comment

by:Interlink_IT
ID: 36967652
Hi,
Thanks for replying, but that gives the same timeout error message when I try and send a 1.8mb file.

Dermot.
0
 

Author Comment

by:Interlink_IT
ID: 36969442
Hi,
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.

Dermot
0
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

 
LVL 5

Expert Comment

by:daveTechSearch
ID: 36969615
For zipping you may want to check out the PowerShell community extentions....

http://pscx.codeplex.com/

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.
0
 
LVL 8

Expert Comment

by:Brent Challis
ID: 37097816
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.

Cheers.
0
 

Author Comment

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

Dermot.
0
 
LVL 8

Accepted Solution

by:
Brent Challis earned 1000 total points
ID: 37104873
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 "sender@domain.com"
$to =   New-Object System.Net.Mail.MailAddress "receiver@domain.com"
 $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")
$message.Attachments.Add($att)

# Set SMTP Server and create SMTP Client
$server = "smtp.gmail.com"
[system.net.mail.smtpclient]$client = New-Object system.net.mail.smtpclient $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 {
      
   $client.Send($message)
   "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()
}
0

Featured Post

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A project that enables an administrator to perform actions within a user session context not just at the time of login but any time later on day(s) or week(s) later.
My attempt to use PowerShell and other great resources found online to simplify the deployment of Office 365 ProPlus client components to any workstation that needs it, regardless of existing Office components that may be needing attention.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…

840 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