I'm not overly familiar with VBS and not sure how to best approach this.
I've got this basic code to work whereby when a value from a machine >= 100 it send out an email. The WinCC triggers this script whenever the tag value changes.
Now, I want to utilise this on a number of other values to monitor parts of machinery and equipment and send out some email alerts.
But, is there any need to replicate the whole email settings code in every script or is there a way that the triggered code can call a global script with the email settings in?
So instead of "Triggered VBS - Check Value - If True - Here's email details - Send Email"
Its more like "Triggered VBS - Check Value - If True - Load Email Setting VBS - Send Email"
Hope that makes sense?
Option Explicit
Function action
Dim TagVari1
Dim TagVari2
Set TagVari1 = HMIRuntime.Tags("TestTag1")
TagVari1.Read
TagVari1.Value = TagVari1.Value +1
Set TagVari2 = HMIRuntime.Tags("TestTag2")
TagVari2.Read
TagVari2.Value = TagVari1.Value
TagVari2.Write
If TagVari2.Value >= 100 Then
Dim objMessage
Set objMessage = CreateObject("CDO.Message")
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.mydomain.com"
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusername") = "my.email#mydomain.com"
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = "30"
objMessage.Configuration.Fields.Update
objMessage.Subject = "WinCC Message"
objMessage.From = "my.email#mydomain.com"
objMessage.To = "recip.email#outlook.com"
objMessage.TextBody = "This is a test message from WinCC......"
objMessage.Send
x=Msgbox("CHP Alarm" ,0, "Tag2 equal or over 100")
End If
End Function
Here's how to include another *.vbs, courtesy of Frank-Peter Schultze
Put this Sub in your main script(s):
'------------------------------------------------------------------------------
'Purpose : Include another VBScript file into the current one.
'Note : Usage: Include("vbsfile.vbs")
'
' Author: Frank-Peter Schultze
' Source: http://www.fpschultze.de/smartfaq+faq.faqid+51.htm
'------------------------------------------------------------------------------
Sub Include(ByVal strFilename)
Dim objFileSys, objFile, strContent
Set objFileSys = WScript.CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSys.OpenTextFile(strFilename, 1)
strContent = objFile.ReadAll
objFile.Close
Set objFileSys = Nothing
ExecuteGlobal strContent
End Sub
'------------------------------------------------------------------------------
Have your email send routine in another script, e.g. MySendMail.vbs
And then somewhere at the start of your main script call it like
Include("Full\Path\To\MySendMail.vbs")
And that's the one caveat: the included filename must be passed to the Sub with its full path including drive.
Related
Dear StackOverflowers.
I know a few programming languages, but unfortunately VBA is not one of them.
I'm trying to make a script that saves the headers from selected mails in Outlook as .msg-files.
I found a script that opens the headers as new messages, but how to I save them as e.g. [senders domain]_[date recieved].msg instead of opening them as new mails?
The script that I have:
Sub ViewInternetHeader()
Dim olItem As Outlook.MailItem, olMsg As Outlook.MailItem
Dim strHeader As String
For Each olItem In Application.ActiveExplorer.Selection
strHeader = GetInetHeaders(olItem)
Set olMsg = Application.CreateItem(olMailItem)
With olMsg
.BodyFormat = olFormatPlain
.Body = strHeader
.Display
End With
Next
Set olMsg = Nothing
End Sub
Function GetInetHeaders(olkMsg As Outlook.MailItem) As String
' Purpose: Returns the internet headers of a message.'
' Written: 4/28/2009'
' Author: BlueDevilFan'
' //techniclee.wordpress.com/
' Outlook: 2007'
Const PR_TRANSPORT_MESSAGE_HEADERS = "http://schemas.microsoft.com/mapi/proptag/0x007D001E"
Dim olkPA As Outlook.PropertyAccessor
Set olkPA = olkMsg.PropertyAccessor
GetInetHeaders = olkPA.GetProperty(PR_TRANSPORT_MESSAGE_HEADERS)
Set olkPA = Nothing
End Function
Use the MailItem.SaveAs method which saves the Microsoft Outlook item to the specified path and in the format of the specified file type. If the file type is not specified, the MSG format (.msg) is used. For example:
Sub SaveAsTXT()
Dim myItem As Outlook.Inspector
Dim objItem As Object
Set myItem = Application.ActiveInspector
If Not TypeName(myItem) = "Nothing" Then
Set objItem = myItem.CurrentItem
strname = objItem.Subject
'Prompt the user for confirmation
Dim strPrompt As String
strPrompt = "Are you sure you want to save the item? " & _
"If a file with the same name already exists, " & _
"it will be overwritten with this copy of the file."
If MsgBox(strPrompt, vbYesNo + vbQuestion) = vbYes Then
objItem.SaveAs Environ("HOMEPATH") & "\My Documents\" & strname & ".txt", olTXT
End If
Else
MsgBox "There is no current active inspector."
End If
End Sub
So you want an MSG file that has no recipients, attachments, subject, etc, only the MIME headers as the body? Why do you want the MSG format then?
You can create an populate a text file using the Scripting.FileSystemObject and use its CreateTextFile method.
Thank you, Eugene.
I managed to put in your code.
But it doesn't give the file a name, it's only called ".msg", and it doesn't work, when I try to select more than one email.
Also, how do I avoid, that it opens a new mail with the header?
I have this script now:
Sub ViewInternetHeader()
Dim olItem As Outlook.MailItem, olMsg As Outlook.MailItem
Dim strHeader As String
For Each olItem In Application.ActiveExplorer.Selection
strHeader = GetInetHeaders(olItem)
Set olMsg = Application.CreateItem(olMailItem)
With olMsg
.BodyFormat = olFormatPlain
.Body = strHeader
.Display
End With
Next
Set olMsg = Nothing
Dim myItem As Outlook.Inspector
Dim objItem As Object
Set myItem = Application.ActiveInspector
If Not TypeName(myItem) = "Nothing" Then
Set objItem = myItem.CurrentItem
strname = objItem.SenderEmailAddress
'Prompt the user for confirmation
Dim strPrompt As String
strPrompt = "Are you sure you want to save the item? " & _
"If a file with the same name already exists, " & _
"it will be overwritten with this copy of the file."
If MsgBox(strPrompt, vbYesNo + vbQuestion) = vbYes Then
objItem.saveas "C:\temp\" & strname & ".msg", OLTXT
End If
Else
MsgBox "There is no current active inspector."
End If
End Sub
Function GetInetHeaders(olkMsg As Outlook.MailItem) As String
Const PR_TRANSPORT_MESSAGE_HEADERS = "http://schemas.microsoft.com/mapi/proptag/0x007D001E"
Dim olkPA As Outlook.PropertyAccessor
Set olkPA = olkMsg.PropertyAccessor
GetInetHeaders = olkPA.GetProperty(PR_TRANSPORT_MESSAGE_HEADERS)
Set olkPA = Nothing
End Function
I want to send the contents of a folder in an email and then delete the folder and the contents.
The code below works, except that it deletes only the contents of the folder and then gives me a Run-time error 70 - Permission denied and leaves the folder. The DeleteAFolder sub works if I run it separately and define strFolder. So it seems that it's somehow an issue of something still being in use, but I can't figure what or how to close it. It's only an empty folder that I can't delete. The files have already been sent in the email and deleted.
Sub SendMultiDocsEmail()
strFolder = "C:\Users\UserID\Desktop\Admin"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strFolder)
Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Testing my files email"
objMessage.From = "myemail#company.com"
objMessage.To = "myemail#company.com"
objMessage.TextBody = "This is a test, files should be attached to this email."
For Each objFile In objFolder.Files
strFileExt = objFSO.GetExtensionName(objFile.Path)
objMessage.AddAttachment objFile.Path
'objFile.Close
' Run-time error 438 - Object doesn't support this property or method
Next
'Configuration Info
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.company.com"
'Server port (typically 25)
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update
objMessage.Send
'strFolder.Close
' Run-time error 424 - Object required
'objFolder.Close
' Run-time error 438 - Object doesn't support this property or method
'Tried adding the Set to Nothing lines - didn't change result
'Set objFSO = Nothing
'Set objFolder = Nothing
DeleteAFolder (strFolder)
End Sub
Sub DeleteAFolder(strFolder)
Set fso = CreateObject("Scripting.FileSystemObject")
fso.DeleteFolder (strFolder)
End Sub
I want to be able to send an attachment file just by dropping it on a script.
I've found this one that sends the file (it works for me):
Set fso=CreateObject("Scripting.FileSystemObject")
strSMTP="smtp.gmail.com"
strSubject="mail#gmail.com"
strSubject2="Attachment file"
strBody="-"
strAttach="FILEPATH"
If fso.FileExists(strAttach) then
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
iConf.Load -1 ' CDO Source Defaults
Set Flds = iConf.Fields
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTP
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "mail#gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
.Update
End With
With iMsg
Set .Configuration = iConf
.To = "mail2#gmail.com"
.CC = ""
.BCC = ""
.From = "mail1#gmail.com"
.Subject = strAttach
.TextBody = strBody
.AddAttachment strAttach
.Send
End With
Set iMsg = Nothing
Set iConf = Nothing
Else
MsgBox "The specified attachment does not exist"
End if
What I need is a modification to this script that allows me to change the 6th line strAttach="FILEPATH" with the path and the extension of the file that im dropping on it and then execute the "send mail script".
Found this two links related to my question, but I don't know how to use them, hope these can help you too.
How to get the fully qualified path for a file in VBScript?
http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/
The first one just shows the filepath and the extension on a new window, but i need it to be overwritten on the 6th line.
Could someone help me? im not a programmer, just want to be able to send the files to my own mail because i need to print them later on another computer.
Sorry for my english. Im not a native speaker. Thanks in advance!
Use Arguments Property (WScript Object):
The Arguments property contains the WshArguments object (a
collection of arguments). Use a zero-based index to retrieve
individual arguments from this collection.
Set fso=CreateObject("Scripting.FileSystemObject")
strSMTP="smtp.gmail.com"
strSubject="mail#gmail.com"
strSubject2="Attachment file"
strBody="-"
''''''''''''''''''''''''''''''''''' strAttach="FILEPATH"
Set objArgs = WScript.Arguments
For ii = 0 to objArgs.Count - 1
SendMyMail fso.GetAbsolutePathName(CStr( objArgs( ii)))
Next
Sub SendMyMail( ByVal strAttach)
If fso.FileExists(strAttach) then
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
iConf.Load -1 ' CDO Source Defaults
Set Flds = iConf.Fields
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTP
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "mail#gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
.Update
End With
With iMsg
Set .Configuration = iConf
.To = "mail2#gmail.com"
.CC = ""
.BCC = ""
.From = "mail1#gmail.com"
.Subject = strAttach
.TextBody = strBody
.AddAttachment strAttach
.Send
End With
Set iMsg = Nothing
Set iConf = Nothing
Else
MsgBox strAttach & vbCrLf & "The specified attachment does not exist"
End if
End Sub
Should work
using file(s) drag&drop as well as
using SendTo… from right-click menu (see shell:sendto: Customize the Send To Menu in Windows 10, 8, 7, or Vista).
Please check Paul Sadowski's article Sending email with CDO to simplify your code.
I'm trying to write an application that sends and receives service calls from a pc to a mobile phone.
I'm using a program called mobile data studio to do most of the work.
Basically the program generates a web-page as its report for a customer and this is mailed to the customer by the system which i have working
The problem is that the system does not wait until the file is generated before it tries to send it as an attachment and i get an error:
CDO.Message1
The system cannot find the file specified.
Position: 58.0
this is the code:
objmessage.Addattachment sFile
Once I click OK on the error the file is then created and if I run the script again it process the mail and the attachment and opens the file if fax is set to "yes" also.
This is all the code:
' Process incoming sessions from Pocket PCs
Function OnIncomingSession (theSession)
' Check if the user indicated a confirmation was desired
If theSession("SendEmail") = "Yes" Then
sendobjMessage theSession
ElseIf theSession("SendFax") = "Yes" Then
sendobjfax theSession
End If
' Set the return value to true to indicate that normal
' processing should continue
OnIncomingSession = True
End Function
Sub sendobjMessage (theSession)
' Get the email address from the session
sEmail = theSession ( "EmailAddress" )
'Get the file name from the session
sFile = "C:\htm\"& theSession("ORN")&"."&"htm"
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")
objMessage.Subject = "Our Company - Service Report" & " " & theSession("rdate")
objMessage.From = """Service Department"" <user#mydomain>"
objMessage.To = sEmail
objMessage.TextBody = "Hi " & theSession("sname") & ","
objmessage.Addattachment sFile
Set objfax = CreateObject("WScript.Shell")
objfax.Run sFile
'==This section provides the configuration information for the remote SMTP server.
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.mydomain.com"
'Type of authentication, NONE, Basic (Base64 encoded), NTLM
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic
'Your UserID on the SMTP server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusername") = "user#mydomain"
'Your password on the SMTP server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
'Server port (typically 25)
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
'Use SSL for the connection (False or True)
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
'Connection Timeout in seconds (the maximum time CDO will try to establish a connection to the SMTP server)
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
objMessage.Configuration.Fields.Update
'==End remote SMTP server configuration section==
objMessage.Send
End Sub
Option Explicit
Dim retval, fso, file
Set fso = CreateObject ("scripting.filesystemobject")
file = "c:\temp\myfile.txt"
retval = waitTilExists (file, true)
MsgBox "return value: " & retval
Function waitTilExists (ByVal file, withRepeat)
' Sleeps until the file exists
' The polling interval will increase gradually, but never rises above MAX_WAITTIME
' Times out after TIMEOUT msec. Will return false if caused by timeout.
Dim waittime, totalwaittime, rep, doAgain
Const INIT_WAITTIME = 20
Const MAX_WAITTIME = 1000
Const TIMEOUT = 5000
Const SLOPE = 1.1
doAgain = true
Do While doAgain
waittime = INIT_WAITTIME
totalwaittime = 0
Do While totalwaittime < TIMEOUT
waittime = Int (waittime * SLOPE)
If waittime>MAX_WAITTIME Then waittime=MAX_WAITTIME
totalwaittime = totalwaittime + waittime
WScript.sleep waittime
If fso.fileExists (file) Then
waitTilExists = true
Exit Function
End If
Loop
If withRepeat Then
rep = MsgBox ("This file does not exist:" & vbcr & file & vbcr & vbcr & "Keep trying?", vbRetryCancel+vbExclamation, "File not found")
doAgain = (rep = vbRetry)
Else
doAgain = false
End If
Loop
waitTilExists = false
End Function
I might have some helpful tools.
I get the impression that you need:
Routine that creates a delay or pause of a certain period of time
Routine that checks for a file's existence.
Here's a routine for creating a delay or pause:
Sub subSleep(strSeconds) ' subSleep(2)
Dim objShell
Dim strCmd
set objShell = CreateObject("wscript.Shell")
'objShell.Run cmdline,1,False
strCmd = "%COMSPEC% /c ping -n " & strSeconds & " 127.0.0.1>nul"
objShell.Run strCmd,0,1
End Sub
Here's a routine for checking for a file's existence:
Function fnFileExists_Bln(strFULLNamee)
Dim strFULLName
strFULLName = strFULLNamee
Dim objFSO
Set objFSO = CreateObject("scripting.filesystemobject")
fnFileExists_Bln = objFSO.FileExists(strFULLName)
End Function ' Function fnFileExists_Bln(strFULLNamee)
I hope this helps.
trying to get some VBA code together to basically be able to run my rules from a button on my toolbar within outlook 2007. The following code runs the rules on my exchange server inbox, which is empty as everything moves to my "Personal Inbox". I just want to change the code below to read my personal inbox and not my exchange mailbox inbox. Have searched on the web and cant find my answer and hence my post -
Sub RunAllInboxRules()
Dim st As Outlook.Store
Dim myRules As Outlook.Rules
Dim rl As Outlook.Rule
Dim count As Integer
Dim ruleList As String
'On Error Resume Next
' get default store (where rules live)
Set st = Application.Session.DefaultStore
' get rules
Set myRules = st.GetRules
' iterate all the rules
For Each rl In myRules
' determine if it's an Inbox rule
If rl.RuleType = olRuleReceive Then
' if so, run it
rl.Execute ShowProgress:=True
count = count + 1
ruleList = ruleList & vbCrLf & rl.Name
End If
Next
' tell the user what you did
ruleList = "These rules were executed against the Inbox: " & vbCrLf & ruleList
MsgBox ruleList, vbInformation, "Macro: RunAllInboxRules"
Set rl = Nothing
Set st = Nothing
Set myRules = Nothing
End Sub
Try this. I have tested on my machine. This logs into the mailbox you are logged onto and runs the rules accordingly
Sub RunAllInboxRules()
Dim objOL As Outlook.Application
Dim st As Outlook.Store
Dim myRules As Outlook.Rules
Dim rl As Outlook.Rule
Dim count As Integer
Dim ruleList As String
Dim fldInbox As Object
Dim gnspNameSpace As Outlook.NameSpace
'On Error Resume Next
' get default store (where rules live)
'Logs into Outlook session
Set objOL = Outlook.Application
Set gnspNameSpace = objOL.GetNamespace("MAPI") 'Outlook Object
'Logs into the default Mailbox Inbox
'set the store to the mailbox
Set st = gnspNameSpace.GetDefaultFolder(olFolderInbox).Store
' get rules
Set myRules = st.GetRules
' iterate all the rules
For Each rl In myRules
' determine if it's an Inbox rule
If rl.RuleType = olRuleReceive Then
' if so, run it
rl.Execute ShowProgress:=True
count = count + 1
ruleList = ruleList & vbCrLf & rl.Name
End If
Next
' tell the user what you did
ruleList = "These rules were executed against the Inbox: " & vbCrLf & ruleList
MsgBox ruleList, vbInformation, "Macro: RunAllInboxRules"
Set rl = Nothing
Set st = Nothing
Set myRules = Nothing
End Sub