×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

JScript to search for specific outlook emails, and download attachments
2

JScript to search for specific outlook emails, and download attachments

JScript to search for specific outlook emails, and download attachments

(OP)
Hi,

I just ported this from our VBScript version to Jscript. More for fun, than anything else.


CODE --> JScript

' /*
'	Search for and Download daily email attachment
'       Get_Attachment_from_Email.wsf
' */

<package>
	<job id="Get_Invoice_Attachment_from_Email">
		<script language="VBScript" src="UDFS.vbs" >
		</script>
		<script language="JScript">
	

			"use strict"
			
			var olFolderInbox = 6
			var ReturnValue_x

			var Outlook_o
			var Namespace_o
			var DefaultFolder_o
			var Items_col
			var Filtered_Items_col
			var Message_o
			var Message_Count_n
			var NthMessage_n

			var Attachment_o
			var Attachment_Count_n
			var Attachment_Item_o

			var version_s

			var Subject_s
			var Body_s
			var ThisFolder
			
			var downloade_folder_s
			var FullFilePath_s

			Subject_s = "Daily Invoices"
			downloade_folder_s = "c:\\FolderToSaveAttachments\\Invoices"
			
			try
				{

					version_s = WScript.Version	// Probably 5.812
					WScript.Echo( "ECMAScript version:" + version_s )  

					Outlook_o = WScript.CreateObject("Outlook.Application")
					Namespace_o = Outlook_o.GetNamespace("MAPI")
					DefaultFolder_o = Namespace_o.GetDefaultFolder(olFolderInbox) // Inbox
					Items_col = DefaultFolder_o.Items
					Filtered_Items_col = Items_col.Restrict("[Subject] = " + Subject_s)
					// We want only emails and attachments from today
					Filtered_Items_col = Filtered_Items_col.Restrict("@SQL=%today(" + String.fromCharCode(34) + "urn:schemas:httpmail:datereceived" + String.fromCharCode(34) + ")%")

					Message_Count_n = Filtered_Items_col.Count
					WScript.Echo( "Message Count " + Message_Count_n )

					for ( NthMessage_n = Message_Count_n ; NthMessage_n > 0 ; NthMessage_n-- )
					{
						Message_o = Filtered_Items_col.Item( NthMessage_n )
						Subject_s = Message_o.Subject
						// WScript.Echo( Subject_s )
						Attachment_Count_n = Message_o.Attachments.Count
						if (Attachment_Count_n>0)
						{
							FileName_s = Message_o.Attachments.Item(1).FileName
							FullFilePath_s = downloade_folder_s + "\\" + FileName_s
							WScript.Echo( FullFilePath_s )
							Message_o.Attachments.Item(1).SaveAsFile( FullFilePath_s )
							break
						
						}
					}
				}
				catch(exception)
				{
					WScript.Echo( "What the...?" )
					WScript.Echo( exception )
					WScript.Quit(-1)
				}
				finally
				{
					WScript.Echo( "Finally." )
					WScript.Quit(0)
				}
			
		</script>
	</job>
</package> 

RE: JScript to search for specific outlook emails, and download attachments

(OP)
JScript.net version, also based on the original VBScript version:

Compile:

CODE --> BatchFile

@Echo Off

@Echo Compiling Get_Attachment_from_Email_Dotnet.js

Rem Release
rem jsc.exe /t:exe /r:System.dll Get_Attachment_from_Email_Dotnet.js

Rem Debug
jsc.exe /t:exe /debug /r:System.dll Get_Attachment_from_Email_Dotnet.js


rem jsc.exe /t:exe /debug /r:Microsoft.Office.Interop.Outlook.dll /r:System.dll Get_Attachment_from_Email_Dotnet.js 

JScript.net code:


CODE --> JScript.net

// Get_Attachment_from_Email_Dotnet.js - Get attachment from today's email with specific subject heading 

import System
import System.Windows.Forms
import Microsoft.Office.Tools
import Microsoft.Office.Interop
import Microsoft.Office.Interop.Outlook
import Microsoft.Office.Interop.Outlook.Application
import Microsoft.Office.Interop.Outlook.MAPIFolder
import Microsoft.Office.Interop.Outlook._NameSpace
import Microsoft.Outlook.Folder
import System.Data

const FOR_APPENDING : int 											= 8
const FOR_WRITING : int 												= 2

const olFolderInbox = 6

var Outlook_o : Object
var Outlook_a : Application

var Namespace_o
var DefaultFolders_o
var Inbox_o

var DefaultFolder_o
var Folder_o : Object
var Folder_col
var Items_col
var Filtered_Items_col
var Message_o
var Message_Count_n
var Attachment_o
var Attachment_Count_n
var Attachment_Item_o
var Items_a
var Subject_s
var Body_s
var ThisFolder
var TheseFolders_o

var FileName_s
var Save_Path_s

var Subject_s = "Daily Invoices"

var Save_Path_s = "c:\\FolderToSaveAttachments\\Invoices"

try
{
	Outlook_o = new ActiveXObject( "Outlook.Application" )
	Namespace_o = Outlook_o.GetNamespace("MAPI")
	Inbox_o = Namespace_o.GetDefaultFolder(olFolderInbox)
	Items_col = Inbox_o.Items
	Filtered_Items_col = Items_col.Restrict("[Subject] = " + Subject_s)
	Filtered_Items_col = Filtered_Items_col.Restrict("@SQL=%today(" + String.fromCharCode(34) + "urn:schemas:httpmail:datereceived" + String.fromCharCode(34) + ")%")
	Message_Count_n = Filtered_Items_col.Count

	for( var NthMessage_n : int = 1; NthMessage_n < Message_Count_n ; NthMessage_n++ )
	{
	  Message_o = Filtered_Items_col.Item( NthMessage_n )
	  Subject_s = Message_o.Subject 
	  Attachment_Count_n = Message_o.Attachments.Count
	  if( Attachment_Count_n > 0 )
	  {
	  	FileName_s = Message_o.Attachments.Item(1).FileName
	 	
	  	LogStatus( " Found " + FileName_s + ". Saving it to " + Save_Path_s )
			Save_Path_s = Save_Path_s + "\\" + FileName_s
	  	Message_o.Attachments.Item(1).SaveAsFile( Save_Path_s )
	  	LogStatus( " Finished saving to " + Save_Path_s )
	  	print( Save_Path_s )
	  }
	}
}
catch(e)
{
		print( e.number & 0xFFFF )	
		print( e.description )
}

function LogStatus( Status_s )
{
	var LogFileName_s
	var objFS
	var objTS
	var ErrorNumber
	var ErrorDescription
	var ErrorSource

	LogFileName_s = ".log"

	try 
	{
		objFS = new ActiveXObject("Scripting.FileSystemObject")
		objTS = objFS.OpenTextFile(LogFileName_s,FOR_APPENDING,true)
		objTS.WriteLine( DateTime.Now + " " + Status_s )
		objTS.Close()
	}
	catch(e)
	{
		print( e.number & 0xFFFF )	
		print( e.description )
		print( "Cannot write to log " + LogFileName_s )
	}
		
} 

RE: JScript to search for specific outlook emails, and download attachments

Nice. I've been looking for something like this, for a month.

Can you forward the original VBScript source that you cloned from? Are you using some specific error handling, in the actual code?

RE: JScript to search for specific outlook emails, and download attachments

(OP)
Hi Eric,

Sure, I'll remove some of the identifying strings, and forward the VBS code over the weekend.

I don't generally do a lot of error handling in VBScript. After I'm familiar with the types of problems that can occur, I just check Statuses, File Existence, and other things that might go wrong. Outside of that, we just let a default error handler happen, which we log to a file and send an email notification.

In this instance, this is a script that only I use daily. So it's not really necessary to report errors, since I can see them if they happen.

RE: JScript to search for specific outlook emails, and download attachments

Yes, useful to Jscript programmers - but this is the VBScript forum, not a Jscript forum. It would probably make more sense to post this in forum216: Javascript

RE: JScript to search for specific outlook emails, and download attachments

(OP)
Here you go, Eric. Let me know if any questions.


CODE --> VBScript

Option Explicit
Const FOR_APPENDING = 8

'GetAttachmentFromOutlook.vbs - Get attachment from today's email, based on subject heading

Const olFolderInbox = 6

Dim Outlook_o
Dim Namespace_o
Dim DefaultFolder_o
Dim Folder_o
Dim Folder_col
Dim Items_col
Dim Filtered_Items_col
Dim Message_o
Dim Message_Count_n
Dim Attachment_o
Dim Attachment_Count_n
Dim Attachment_Item_o
Dim Items_a
Dim Subject_s
Dim Body_s
Dim ThisFolder
Dim TargetFolderName_s
Dim TheseFolders_o

Dim DayFilter_s

Dim FileName_s
Dim Save_Path_s

Dim ErrorNumber
Dim ErrorDescription
Dim ErrorSource



' On Error Resume Next

TargetFolderName_s = "Inbox"
Subject_s = "Daily Invoices"

Save_Path_s = "C:\FolderToSaveAttachments\Invoices"

LogStatus( Now & " Reading Outlook, searching for files from today " )
Set Outlook_o = CreateObject("Outlook.Application")
Set Namespace_o = Outlook_o.GetNamespace("MAPI")
Set DefaultFolder_o = Namespace_o.GetDefaultFolder(olFolderInbox) 'Inbox
Set Items_col = DefaultFolder_o.Items
Set Filtered_Items_col = Items_col.Restrict("[Subject] = " & Subject_s)
' Filter emails only from today
Set Filtered_Items_col = Filtered_Items_col.Restrict("@SQL=%today(""urn:schemas:httpmail:datereceived"")%")

Message_Count_n = Filtered_Items_col.Count

For Message_Count_n = Filtered_Items_col.Count to 1 step -1
  Set Message_o = Filtered_Items_col.Item(Message_Count_n)
  Body_s = Message_o.Subject 
  Attachment_Count_n = Message_o.Attachments.Count
  If Attachment_Count_n > 0 Then
  	FileName_s = Message_o.Attachments.Item(1).FileName
  	LogStatus( Now & " Found " & FileName_s & ". Saving it to " & Save_Path_s )
  	Message_o.Attachments.Item(1).SaveAsFile Save_Path_s  & "\" & FileName_s
  	LogStatus( Now & " Finished saving to " & Save_Path_s  & "\" & FileName_s )
  End If

Next 


Set Outlook_o = Nothing
Set Namespace_o = Nothing
Set DefaultFolder_o = Nothing


WScript.Quit


Sub LogStatus( Status_s )
Dim ApLogFileName_s
Dim objFS
Dim objTS
Dim ErrorNumber
Dim ErrorDescription
Dim ErrorSource


LogFileName_s = "Invoice.log"


On Error Resume Next
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objTS = objFS.OpenTextFile(ApLogFileName_s,FOR_APPENDING,True)
If Err.number = 0 Then
	objTS.WriteLine Now & " " & Status_s
	objTS.Close
Else
	ErrorNumber = Err.number
	ErrorDescription = Err.Description
	ErrorSource = Err.Source
	Err.Clear

	WScript.Echo "Cannot open Log " & ApLogFileName_sApLogFileName_s & ", " & Err.Description
End If
	
Set objTS = Nothing
Set objFS = Nothing

End Sub 

RE: JScript to search for specific outlook emails, and download attachments

Thanks, Don. I searched for several weeks, and I didn't expect to find nearly exactly what I was looking for.

Are you using a text editor for VBScript, or an ide?

RE: JScript to search for specific outlook emails, and download attachments

(OP)
Eric,


VBSEdit, https://www.vbsedit.com.

Been using it for years. Customer service very prompt. They have lots of samples, both online and included in their distribution.

Also - relevant to this thread - it supports Windows Scripting Hosts in general including JScript, and mixing VBScript and JScript.

Regards,

RE: JScript to search for specific outlook emails, and download attachments

Thanks for all your help, Don. Enjoy the rest of the holiday weekend.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login


Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close