I look for an email in Outlook using VBA in Access. It doesn't work all the time.
I wonder if I do not declare my variables officially, or do not open Outlook properly.
Also, is there a way to open Outlook, refresh the inbox folder, and then begin scanning?
The error is either one of two things, the remote server you are trying to connect to is not available", or "object not declared" as if the Outlook application was never opened.
Dim ns As Outlook.NameSpace
Dim objOL As Outlook.Application
Dim folder As MAPIFolder
Dim item As Object
Dim msg As MailItem
Dim objAttachments As Outlook.Attachments
Set objOL = CreateObject("Outlook.Application")
'The line below will error out occasionally
' with a remote serve not available...
Set ns = Session.Application.GetNamespace("MAPI")
Set folder = ns.GetDefaultFolder(olFolderInbox)
For Each item In folder.Items
DoEvents
If (item.Class = olMail) And (item.UnRead) Then
' This message has not been read. Display it modally
Set msg = item
'Debug.Print (msg.Subject)
'Debug.Print (msg.SenderEmailAddress)
tempString = CStr(msg.Subject)
If Mid(tempString, 1, 4) = "qqqq" Then
'Debug.Print (tempString)
'create new directory
If updateFlag = 0 Then
'this checks if the directory already exists,
' if it does just skip creating the directory since we do not
' want to override previous saved attached inventory files.
If Dir(strFolderpath, vbDirectory) = "" Then
Createdir True, strFolderpath
End If
End If
updateFlag = 1
'Debug.Print msg.Subject
'instantiate attachments object for each openned email
Set objAttachments = msg.Attachments
lngCount = objAttachments.Count
'if you want to open all the emails uncomment next line
'msg.Display True
For i = lngCount To 1 Step -1
' Save attachment before deleting from item.
' Get the file name.
strFile = objAttachments.item(i).FileName
' Combine with the path to the Temp folder.
strFile = strFolderpath & "\" & strFile
WriteLogFile "File saved from blabla#blbl inbox, file path: " & strFile
' Save the attachment as a file.
objAttachments.item(i).SaveAsFile strFile
Next i
msg.UnRead = False
End If
End If
Next
'close the outlook application.
'objOL.Quit
I tried opening Outlook, then closing it and reopening it, but that doesn't work as well. Is there a more proper way to open Outlook? And how to refresh the inbox once open, wait for refresh to complete, and then scan inbox?
Related
I used to use below VBscript to send files by mail as attachments to be able to add my signature in the e-mail message.
Since about two weeks the VBscript is showing an error every time I try to send a file. I tried to use normal "send to/mail recipient" and it works fine.
Would you advice how can this be solved?
Code:
Option Explicit
Dim objArgs, OutApp, oNameSpace, oInbox, oEmailItem, olMailItem
Dim a, oAttachments, subjectStr, olFormatHTML
olMailItem = 0
olFormatHTML = 2
Set objArgs = WScript.Arguments 'gets paths of selected files
Set OutApp = CreateObject("Outlook.Application") 'opens Outlook
Set oEmailItem = OutApp.CreateItem(olMailItem) 'opens new email
For a = 0 to objArgs.Count - 1
Set oAttachments = oEmailItem.Attachments.Add(objArgs(a))
subjectStr = subjectStr & Right(objArgs(a),Len(objArgs(a))-(InStrRev(objArgs(a),"\"))) & ", " 'recreates the default Subject e.g. Emailing: file1.doc, file2.xls
Next
If subjectStr = "" then subjectStr = "No Subject "
oEmailItem.Subject = "Emailing: " & Left(subjectStr, (Len(subjectStr)-2))
oEmailItem.BodyFormat = olFormatHTML
oEmailItem.Display
Error message:
Unable to execute - arguments list is too long
I need to send an email from an MS Access database with an attachment (not an Access object, but a separate file), but not tied to any one email software (Groupwise, Outlook, etc). I have found code to send an email with an attachment using Groupwise and Outlook, and there is the generic DoCmd.SendObject which only appears to support attaching Access objects. Is there a way to send an email from Access with an attachment, regardless of the email client configured on the user's PC?
Rationale: There's complications with software rollout here. The machine I work on has Access 2013 and Outlook 2013 installed. The users of the database are running Access 2010, but when I compile the database into a .accde in 2013, it does not work on 2010. The only way I can get it to work is to compile it on a much older PC also running Access 2010. However, this old PC does not have Outlook and IT won't/can't install Outlook on it. This means I can't compile the database using the Outlook library, as there is no Outlook library on the machine.
Here is code I use to send e-mails using Gmail:
Public Function SendEmailViaGmail(SendTo As String, Optional Subject As String = "", Optional TextBody As String = "", Optional ReplyTo As String = "", Optional AttachedFiles As Variant = "") As String
On Error GoTo send_emailErr
Dim ErrNum As Long
Dim ErrDes As String
SendEmailViaGmail = ""
ErrNum = 0
Set cdomsg = CreateObject("CDO.message")
With cdomsg.Configuration.Fields
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'NTLM method
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = 587
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = sendusername '
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = sendpassword
.Update
End With
' build email parts
With cdomsg
.To = SendTo
.FROM = sendusername
.Subject = Subject
.TextBody = TextBody & vbCrLf & vbCrLf & vbCrLf & "--" & vbCrLf & "Sent using Marlan Data-Systems"
If IsArray(AttachedFiles) Then
For Each AttachedFile In AttachedFiles
If Len(AttachedFile) > 3 Then .AddAttachment AttachedFile
Next
Else
If Len(AttachedFiles) > 3 Then .AddAttachment AttachedFiles
End If
.send
End With
SendEmailViaGmail = "Done!"
send_emailExit:
Set cdomsg = Nothing
Exit Function
send_emailErr:
ErrNum = Err.Number
ErrDes = Err.Description
Select Case Err.Number
Case -2147220977 'Likely cause, Incorrectly Formatted Email Address, server rejected the Email Format
SendEmailViaGmail = "Please Format the Email Address Correctly."
Case -2147220980 'Likely cause, No Recipient Provided (No Email Address)
SendEmailViaGmail = "Please Provide an Email Address"
Case -2147220960 'Likely cause, SendUsing Configuration Error
SendEmailViaGmail = "SendUsing Configuration Error"
Case -2147220973 'Likely cause, No Internet Connection
SendEmailViaGmail = "Please Check Internet Connection"
Case -2147220975 'Likely cause, Incorrect Password
SendEmailViaGmail = "Please Check Password"
Case Else 'Report Other Errors
SendEmailViaGmail = ""
End Select
SendEmailViaGmail = SendEmailViaGmail & " Error number: " & Err.Number & " Description: " & Err.Description
'If ErrNum = -2147220975 Then
' cdomsg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = 465
' Resume
'End If
Resume send_emailExit
End Function
AttachedFiles is a String, or an Array of Strings, representing full paths to file or files that are to be attached to the email.
CDO.message is a Microsoft windows object.
You can replace value of smtpserver to some other mailing service. If you do so, please be sure to modify other parameters as well.
Code is based on code I found on the web.
i am trying to send outlook mail using vb script language in testcomplete. i am able to send but if the outlook is opened in my PC then only mail will be sent and if the oulook is not opened in my pc,my mail will not be sent untill opening the outllok even after executing this script
here is my code:
Function SendMail
Dim objOutLook, NamespaceMAPI,objNewMail, fso, SendReceiveControls
Dim strTo,strCc ,strBcc ,strSubject, AccountName,strAttachmentPath
strSubject="test"
strTo=yyy#yy.com
strCc=XXX#XX.com
strBcc =zzz#zzz.com
strAttachmentPath="c:\text.txt"
If strTo ="" and strCc = "" and strBcc =""Then
Exit function
ElseIf strSubject =""Then
Exit function
End If
Set objOutLook = CreateObject("Outlook.Application")
Set NamespaceMAPI = objOutLook.GetNamespace("MAPI")
Set objNewMail = objOutLook.CreateItem(olMailItem)
objOutLook.DisplayAlerts =True
objNewMail.TO = strTo
objNewMail.CC = strCc
objNewMail.BCC=strBcc
objNewMail.Subject = strSubject
objNewMail.Body = strMsg
If strAttachmentPath <> "" Then
Set fso =CreateObject("Scripting.FileSystemObject")
If fso.FileExists(strAttachmentPath) Then
objNewMail.Attachments.Add(strAttachmentPath)
objNewMail.display
Else
msgbox "Attachment File Does not exists"
End If
End If
AccountName="XXXXXX#XXXX.com"
' Finding the "Send/Receive" control
Set SendReceiveControls = NamespaceMAPI.GetDefaultFolder("Inbox")._
CommandBars("STANDARD").Controls("Send/Receive")
Set Item = Nothing
'msgbox "send:"&SendReceiveControls.Controls.Count
For I = 1 To SendReceiveControls.Controls.Count
If InStr(SendReceiveControls.Controls(I).Caption, AccountName) > 0 Then
Set Item = SendReceiveControls.Controls(I)
'msgbox "send1"&SendReceiveControls.Controls(I)
Exit For
End If
Next
' Executing the "Send/Receive" action
Item.Controls(1).Execute()
objOutLook.Quit
''''''' Releasing objects '''''''
Set objOutLook =Nothing
Set objNewMail = Nothing
Set fso = Nothing
End Function
please suggest me how to handle this...thanks in advance
Do you really need to send it with outlook?
I use this javascript code to send the email, then, in outlook, you just need to mark it as not spam, otherwise, it goes directly to the spam inbox
function SendEmail(mFrom, mTo, mSubject, mBody, username, password)
{
var i, schema, mConfig, mMessage;
try
{
schema = "http://schemas.microsoft.com/cdo/configuration/";
mConfig = Sys.OleObject("CDO.Configuration");
mConfig.Fields.Item(schema + "sendusing") = 2; // cdoSendUsingExchange
mConfig.Fields.Item(schema + "smtpserver") = "STMP SERVER ADDRESS HERE"; // SMTP server
mConfig.Fields.Item(schema + "smtpserverport") = 25; // Port number
mConfig.Fields.Item(schema + "smtpauthenticate") = 1; // Authentication mechanism
mConfig.Fields.Item(schema + "sendusername") = username; // User name (if needed)
mConfig.Fields.Item(schema + "sendpassword") = password; // User password (if needed)
mConfig.Fields.Update();
mMessage = Sys.OleObject("CDO.Message");
mMessage.Configuration = mConfig;
mMessage.From = mFrom;
mMessage.To = mTo;
mMessage.Subject = mSubject;
mMessage.HTMLBody = mBody;
mMessage.Send();
}
catch (exception)
{
Log.Error("E-mail cannot be sent", exception.description);
return false;
}
Log.Message("Message to <" + mTo + "> was successfully sent");
return true;
}
Try objNewMail.Body.Send instead of trying to execute the send and receive button. Here's a simple example:
Function SendMail()
Dim objOutlook, objNewMail
Set objOutLook = CreateObject("Outlook.Application")
Set objNewMail = objOutLook.CreateItem(olMailItem)
objNewMail.TO = "myrecip#test.com"
objNewMail.Subject = "test"
objNewMail.Body = "test"
objNewMail.Send
End Function
I have been tearing my hair out over the last few days in trying to get this macro to work consistantly on the Windows scheduler.
Basically the workflow is as follows:
1) Windows Scheduler - Daily, uses Admin user credentials
2) Batch file - Reloads using /l
3) Reloads Qlikview application, which has triggers on post reload to save a pdf and email it using PDF Xchange and an html formatted e-mail to cover mobile.
I am getting such inconsistent behaviour that I cannot isolate the problem to any particular one thing. Sometimes it works, sometimes it doesn't. More often than not it fails on the Windows scheduler. There is no error since QV has just thrown up the VBScript window in the hidden process.
I've been changing permissions, which helped me reach a level of inconsistent performance as opposed to no performance.
In addition, it appears that you cannot pass variables to the PDF Xchange printer.
The code in the macro is as follows:
sub ExportPDF
printReportPDF "\\SGH-SRV-FPS1\S-Drive\eCommerce\Data Analyst\Reporting\Daily E-Commerce Report\E-Commerce Daily Report.pdf"
ActiveDocument.GetApplication.Sleep 2000
ActiveDocument.PrintReport "RP01", "PDF-XChange 3.0"
ActiveDocument.GetApplication.Sleep 8000
end sub
Function printReportPDF(pdfOutputFile)
Set WSHShell = CreateObject("WScript.Shell")
WSHShell.RegWrite "HKCU\Software\Tracker Software\PDF-XChange 3.0\OutputFile", pdfOutputFile, "REG_SZ"
WSHShell.RegWrite "HKCU\Software\Tracker Software\PDF-XChange 3.0\BypassSaveAs", "1", "REG_SZ"
Set WSHShell = nothing
End function
Sub ExportEmail
Dim strvDest 'as string
strvDest = ActiveDocument.Variables("vDestination").GetContent().String
msgbox(strvDestination)
Define report variables
get the date as a serial for the filename output
Export an Object
Set obj = ActiveDocument.ActiveSheet.SheetObjects("TX25")
Set obj1 = ActiveDocument.ActiveSheet.SheetObjects("TX17")
Set obj2 = ActiveDocument.ActiveSheet.SheetObjects("TX18")
Set obj3 = ActiveDocument.ActiveSheet.SheetObjects("TX15")
Set obj5 = ActiveDocument.ActiveSheet.SheetObjects("CH62")
Set obj6 = ActiveDocument.ActiveSheet.SheetObjects("TX16")
Set obj8 = ActiveDocument.ActiveSheet.SheetObjects("CH58")
Set obj9 = ActiveDocument.ActiveSheet.SheetObjects("TX31")
Set obj10 = ActiveDocument.ActiveSheet.SheetObjects("CH69")
msgbox("defined objects")
obj.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainLogo.jpg"
obj1.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainHeader.jpg"
obj2.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\DateRange.jpg"
obj3.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader.jpg"
obj5.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\DailySiteDetail.jpg"
obj6.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader2.jpg"
obj8.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetail.jpg"
obj9.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader3.jpg"
obj10.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetailLW.jpg"
msgbox("created objects")
Dim objEmail
Const cdoSendUsingPort = 2 Send the message using SMTP
Const cdoAnonymous = 0 Do not authenticate
Const cdoBasic = 1 basic (clear-text) authentication
Const cdoNTLM = 2 NTLM
Const SMTPServer = "xxxx" ' changed for public consumption
Const SMTPPort = 25 ' Port number for SMTP
Const SMTPTimeout = 120 ' Timeout for SMTP in seconds
Set objEmail = CreateObject("CDO.Message")
Set objConf = objEmail.Configuration
Set objFlds = objConf.Fields
With objFlds
———————————————————————
SMTP server details
removed the html links down to this being my first post
.Update
———————————————————————
End With
allow the passing of a variable from the load script to define the distribution list
if len(strvDest) > 0 then
msgbox("variable exists "&strvDest)
objEmail.To = strvDest
else
msgbox("variable does not exist")
objEmail.To = "xxxx" 'changed for public consumption
end if
objEmail.From = "xxxx" 'changed for public consumption
objEmail.Subject = "Daily Reporting"
HTML = "<!DOCTYPE HTML PUBLIC ""-//IETF//DTD HTML//EN"">" & chr(13) & chr(10)
HTML = HTML & "<html>"
HTML = HTML & "<head>"
HTML = HTML & "<meta http-equiv=""Content-Type"" content=""text/html; charset=iso-8859-1"">"
HTML = HTML & "<title>Automated Emails!</title>"
HTML = HTML & "</head>"
HTML = HTML & "<body bgcolor=""#FFFFFF"">"
HTML = HTML & "<br> <img src=""cid:MainLogo.jpg"" >"
HTML = HTML & "<br> <img src=""cid:MainHeader.jpg"" >"
HTML = HTML & "<br> <img src=""cid:DateRange.jpg"" >"
HTML = HTML & "<br> <img src=""cid:SecondaryHeader.jpg"" >"
HTML = HTML & "<br> <img src=""cid:DailySiteDetail.jpg"" >"
HTML = HTML & "<br> <img src=""cid:SecondaryHeader2.jpg"" >"
HTML = HTML & "<br> <img src=""cid:WeeklySiteDetail.jpg"" >"
HTML = HTML & "<br> <img src=""cid:SecondaryHeader3.jpg"" >"
HTML = HTML & "<br> <img src=""cid:WeeklySiteDetailLW.jpg"" >"
HTML = HTML & "<p>"
HTML = HTML & "</p>"
HTML = HTML & "</body>"
HTML = HTML & "</html>"
Set objBP = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainLogo.jpg", "MainLogo.jpg", CdoReferenceTypeName)
objBP.Fields.Item("urn:schemas:mailheader:Content-ID") = "<MainLogo.jpg>"
objBP.Fields.Update
Set objBP1 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainHeader.jpg", "MainHeader.jpg", CdoReferenceTypeName)
objBP1.Fields.Item("urn:schemas:mailheader:Content-ID") = "<MainHeader.jpg>"
objBP1.Fields.Update
Set objBP2 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\DateRange.jpg", "DateRange.jpg", CdoReferenceTypeName)
objBP2.Fields.Item("urn:schemas:mailheader:Content-ID") = "<DateRange.jpg>"
objBP2.Fields.Update
Set objBP3 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader.jpg", "SecondaryHeader.jpg", CdoReferenceTypeName)
objBP3.Fields.Item("urn:schemas:mailheader:Content-ID") = "<SecondaryHeader.jpg>"
objBP3.Fields.Update
Set objBP5 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\DailySiteDetail.jpg", "DailySiteDetail.jpg", CdoReferenceTypeName)
objBP5.Fields.Item("urn:schemas:mailheader:Content-ID") = "<DailySiteDetail.jpg>"
objBP5.Fields.Update
Set objBP6 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader2.jpg", "SecondaryHeader2.jpg", CdoReferenceTypeName)
objBP6.Fields.Item("urn:schemas:mailheader:Content-ID") = "<SecondaryHeader2.jpg>"
objBP6.Fields.Update
Set objBP8 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetail.jpg", "WeeklySiteDetail.jpg", CdoReferenceTypeName)
objBP8.Fields.Item("urn:schemas:mailheader:Content-ID") = "<WeeklySiteDetail.jpg>"
objBP8.Fields.Update
Set objBP9 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader3.jpg", "SecondaryHeader3.jpg", CdoReferenceTypeName)
objBP9.Fields.Item("urn:schemas:mailheader:Content-ID") = "<SecondaryHeader3.jpg>"
objBP9.Fields.Update
Set objBP10 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetailLW.jpg", "WeeklySiteDetailLW.jpg", CdoReferenceTypeName)
objBP10.Fields.Item("urn:schemas:mailheader:Content-ID") = "<WeeklySiteDetailLW.jpg>"
objBP10.Fields.Update
Set objBPDoc = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\Qlikview Printing.pdf", "Qlikview Printing.pdf", CdoReferenceTypeName)
objBPDoc.Fields.Item("urn:schemas:mailheader:Content-ID") = "<Qlikview Printing.pdf>"
objBPDoc.Fields.Update
objEmail.HTMLBody = HTML
msgbox("attached objects")
objEmail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objEmail = Nothing
ActiveDocument.Save
Application.Quit
End Sub
I cannot ask questions so I will try to give you an answer of the bat.
Firstly, does it reload manually from the QV Document? If yes then
Then you are most probably using 2 differant usernames to reload, please make sure that the username used to reload via scheduler has permissions on every single file the VB is accessing.
Did you set the permissions on the VB side to the following:
Requested Module Security = System Access
Current Local Security = Allow system access
Lastly, On the General screen of the scheduled task, under security options at the bottom. Make sure "Run with highest privileges" is unticked, this sometimes causes issues.
I have a vbscript ,which sends the folder contents as attachments to my email but the problem is i am unable to specify the path of windows folder because the windows path is different for different computers.
In my code following works
Const PATH = "C:\windows\Folder1\"
but since path is different for different machines. i tried following but no success
Const PATH = "%windows%\Folder1\"
Here is the full vbscript code
Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory.
Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network).
Const cdoAnonymous = 0 'Do not authenticate
Const cdoBasic = 1 'basic (clear-text) authentication
Const cdoNTLM = 2 'NTLM
Set objMessage = CreateObject("CDO.Message")
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFolder
Dim oFile
Dim oFiles
Const PATH = "%windows%\Folder\" 'This method not working!!!!!
Set oFolder = fso.GetFolder(PATH)
Set oFiles= oFolder.files
objMessage.Subject = "This is the email subject"
objMessage.From = "mailSender#MyMail.com"
objMessage.To = ""
objMessage.TextBody = "This is the body of the email. I’m fairly unoriginal"
For Each oFile in oFolder.files
objMessage.AddAttachment PATH & oFile.name
Next
'==This section will provide the configuration information for the remote SMTP server.
'==End remote SMTP server configuration section==
objMessage.Send
when the configuration information for the remote SMTP server the code works perfectly.
how will i specify the windows,programfiles,desktop(special folders) in this script??
>> WScript.Echo CreateObject("WScript.Shell").ExpandEnvironmentStrings("%windir%")
>>
C:\WINDOWS
>> WScript.Echo CreateObject("WScript.Shell").SpecialFolders("Desktop")
>>
C:\Documents and Settings\eh\Desktop
UPDATE:
sample usage:
Option Explicit
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
'Your problem in a nutshell
'Const PATH = "c:\windows\system" ' fails on systems with %windir% <> c:\windows
'Const PATH = "%windir%\system" ' fails with "Path not found" (FSO does not expand env vars)
Dim goWS : Set goWS = CreateObject("WScript.Shell")
' PATH can't be a Const, because Consts can be initialized with literals only
' I use the prefix "cs" to indicate "constant string - keep your fingers off!"
Dim csPATH : csPATH = goWS.ExpandEnvironmentStrings("%windir%\system")
Dim csDESKT : csDESKT = goWS.SpecialFolders("desktop")
WScript.Echo "# of files in system folder:", goFS.GetFolder(csPATH).Files.Count
WScript.Echo "# of files in desktop:", goFS.GetFolder(csDESKT).Files.Count
output:
cscript specfolders.vbs
# of files in system folder: 27
# of files in desktop: 49
Due to windows security architecture its not a good practice to do as you are trying. I would start from SpecialDirectories Class : http://msdn.microsoft.com/en-us/library/Microsoft.VisualBasic.FileIO.SpecialDirectories.aspx
If your objective is to send email with attachment? I will use the following example :
Public Shared Function SendMail(strFrom As String, strTo As String, strSubject As String, strMsg As String) As Boolean
Try
' Create the mail message
Dim objMailMsg As New MailMessage(strFrom, strTo)
objMailMsg.BodyEncoding = Encoding.UTF8
objMailMsg.Subject = strSubject
objMailMsg.Body = strMsg
Dim at As New Attachment(Server.MapPath("~/Uploaded/txt.doc"))
objMailMsg.Attachments.Add(at)
objMailMsg.Priority = MailPriority.High
objMailMsg.IsBodyHtml = True
'prepare to send mail via SMTP transport
Dim objSMTPClient As New SmtpClient()
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis
objSMTPClient.Send(objMailMsg)
Return True
Catch ex As Exception
Throw ex
End Try
End Function
Or
If you want to use folder location to attach the file. Firstly I will not use c:\windows\folder1 as a location for files. As this folder contains all your/clients system files and you might run into security issues.
Insert the following code :
Your code
\\ Const PATH = "%windows%\Folder\" 'This method not working!!!!!
\\ Set oFolder = fso.GetFolder(PATH)
Use the following
string PATH = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Returns the string "C:\Users\Owner\Documents". here you can add new folder in above code. use concatenation like this & "\" & "Folder1"
Hope this is helpful...