VBscript - Body of text file into Email - email

i m using the following script to send a few emails during the day, it takes one or more parameters (there are a few versions) and is called by a .bat file. The script is :
Const schema = "http://schemas.microsoft.com/cdo/configuration/"
Const cdoBasic = 2
Const cdoSendUsingPort = 2
Dim oMsg, oConf
Dim sDateTimeStamp
Set args = WScript.Arguments
arg1 = args(0)
' E-mail properties
Set oMsg = CreateObject("CDO.Message")
oMsg.From = "myemail#gmail.com" ' or "Sender Name <from#gmail.com>"
oMsg.To = "otheremail#gmail.com" ' or "Recipient Name <to#gmail.com>"
oMsg.Subject = "System Message"
oMsg.BodyPart.Charset = "Windows-1253"
oMsg.Textbody = "Attached files." & vbcrlf & _
"This on a new line" & vbcrlf & _
"This on yet another"
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const FileToBeUsed = "DIRTEST.TXT"
Dim fso, f, g
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(FileToBeUsed, ForReading)
g = f.ReadAll
f.Close
Set f = Nothing
Set fso = Nothing
' GMail SMTP server configuration and authentication info
Set oConf = oMsg.Configuration
oConf.Fields(schema & "smtpserver") = "gmail.com" 'server address
oConf.Fields(schema & "smtpserverport") = 587 'port number
oConf.Fields(schema & "sendusing") = cdoSendUsingPort
oConf.Fields(schema & "smtpauthenticate") = cdoBasic 'authentication type
oConf.Fields(schema & "smtpusessl") = False 'use SSL encryption
oConf.Fields(schema & "sendusername") = "mymy#gmail.com" 'sender username
oConf.Fields(schema & "sendpassword") = "XXXXXX" 'sender password
oConf.Fields.Update()
'base64
' send message
oMsg.Send()
' Return status message
If Err Then
resultMessage = "ERROR " & Err.Number & ": " & Err.Description
Err.Clear()
Else
resultMessage = "Success Notification Message sent succesfully."
End If
Wscript.echo(resultMessage)
Right now the text body is set to :
Attached Files
This is a new line
This is yet another
I would like to interject a directory listing between line 1 and 2, either directly or by saving the directory listing in a text file, then putting the contents of said file in the email body, like so :
Attached Files
06/10/2016 <TIME> 13.000 Name1.txt
06/10/2016 <TIME> 300.000 Name2.pdf
06/10/2016 <TIME> 150.000 Name3.pdf
06/10/2016 <TIME> 5.000.000 Name4.pdf
This is a new line
This is yet another
EDIT : The above code succesfully appends the dir list to the mail subject, but also appends a batch of gibberish characters at the top.

The script is self explanatory
Edit: Formated size. Also note it give the size of folders. This can be slow, you may want to omit for folders. For instance the first time you run above code (on c:\ folder) windows has to read every folder into memory. That takes a while. Second time you run it all folders will be in the disk cache and it will be super fast.
Edit2 The VBS help file has recently been taken down at MS web site. It is available on my skydrive at https://1drv.ms/f/s!AvqkaKIXzvDieQFjUcKneSZhDjw It's called script56.chm.
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set fldr = fso.GetFolder("c:\")
Set Fls = fldr.files
Set Fldrs = fldr.subfolders
For Each thing in Fls
A= A & vbtab & thing.name & vbtab & thing.attributes & vbtab & FormatNumber(thing.size, 0) & vbtab & Thing.DateLastModified & vbcrlf
Next
For Each thing in Fldrs
A= A & vbtab & thing.name & vbtab & thing.attributes & vbtab & FormatNumber(thing.size, 0) & vbtab & Thing.DateLastModified & vbcrlf
Next
msgbox a
msgbox a

Related

CDO no longer working on Windows Server at network solutions

I am using a server side script using CDO on Network solution that is now failing with a '500 server error' Have they changed their Windows servers?
This code works fine on some other domains hosted by Network solutions. I tried changing to localhost and the server port to 25 with no luck.
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
Dim cdoConfig, cdoMessage, sch, nProfileID, sFName, sLName, sEmail, sBCC, sFromEmail, sMessage, Optin
nProfileID = Request.Form("profileID")
sFName = Request.Form("fname")
sLName = Request.Form("lname")
sFromEmail = Request.Form("email")
sMessage = Request.Form("message")
Optin = Request.Form("optin")
'sAction = "email_form_work.asp?profileID=" & nProfileID
sEmail = "m.hill#secretagency.com" 'generic email account *** change to info#bglawde.com
sBCC = "hillcreative#comcast.net"
sch = "http://schemas.microsoft.com/cdo/configuration/"
Set cdoConfig = CreateObject("CDO.Configuration")
With cdoConfig.Fields
'Set CDO Port
.Item(sch & "sendusing") = 1
'Set mailserver name either IP address, mail.yoursite.com or localhost
.Item(sch & "smtpserver") = "smtp.secretagency.com"
'Set SMTP port which is 25 by default
.Item(sch & "smtpserverport") = 2525
'Set number of seconds before timeout
.Item(sch & "smtpconnectiontimeout") = 60
.update
End With
Set cdoMessage = CreateObject("CDO.Message")
With cdoMessage
Set .Configuration = cdoConfig
.From = sFromEmail
.To = sEmail
.CC = ""
'use this to send a blind copy
.BCC = sBCC
.Subject = ""
'Send the email in text format *comment out HTML
.TextBody = sFName & " " & sLName & " has sent you the following message:" & vbCRLF & vbCRLF & sMessage & vbCRLF
.Send
End With
set cdoMessage = nothing
set cdoConfig = nothing
'************ Mail ends here ********************
%>
Problem solved. Network solutions Windows Server will only work with CDO when employing Authentication:
cdoSMTPAuthenticate, cdoSendUsername, cdoSendPassword must be defined.

Emailing with Classic ASP

Aim:
Email clients from admin#companywebsite.com
Issue:
Firstly let me say I am a .Net developer but I have been asked to look at the below to support my clients existing site they are having issues in as the new one will not be up for 6 months.
The Server it is sat on is sat on a different server domain i.e. outsourcedcompany.companywebsite.com and when we email out the emails are going to info#companywebsite.com etc. but not to say info#gmail.com
How can I help myself:
I will be able to set up admin#companywebsite.com on the server to send out emails to the client if we need to and it helps
Code:
'This section provides the configuration information for the remote SMTP server.
'Custom Code #211-73254650
' -------------------------
Dim FireUPRN
Dim FRADate
Dim SurveyCompany
Dim Assessor
Dim TaskType
Dim Task
Dim ActionType
Dim Priority
Dim RecommendationDate
Dim TaskAllocatedDate
Dim TaskAllocatedTo
Dim TargetDate
Dim TaskStatus
Dim TaskComments
Dim Photo
Dim AssigneeEmailAddress
Dim Bodytxt
FireUPRN = Request.Form("FireUPRN")
FRADate = Request.Form("FRADate")
SurveyCompany = Request.Form("SurveyCompany")
Assessor = Request.Form("Assessor")
TaskType = Request.Form("TaskType")
Task = Request.Form("Task")
ActionType = Request.Form("ActionType")
Priority = Request.Form("Priority")
RecommendationDate = Request.Form("RecommendationDate")
TaskAllocatedDate = Request.Form("TaskAllocatedDate")
TaskAllocatedTo = Request.Form("TaskAllocatedTo")
TargetDate = Request.Form("TargetDate")
TaskStatus = Request.Form("TaskStatus")
TaskComments = Request.Form("TaskComments")
Photo = Request.Form("Photo")
AssigneeEmailAddress = Request.Form("AssigneeEmailAddress")
Dim ObjSendMail
Set ObjSendMail = CreateObject("CDO.Message")
'This section provides the configuration information for the remote SMTP server.
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'Send the message using the network (SMTP over the network).
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.COMPANY-NAME.com"
'changed 25 to 465
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
'Use SSL for the connection (True or False)
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
'Timeout
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
'If your server requires outgoing authentication uncomment the lines bleow and use a valid email address and password.
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'basic (clear-text) authentication
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = "webmaster#COMPANY-NAME.com"
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "villa1982"
ObjSendMail.Configuration.Fields.Update
'End remote SMTP server configuration section==
ObjSendMail.To = Request.Form("AssigneeEmailAddress")
ObjSendMail.Subject = "Assigned Fire Risk Assessment Task, which must be carried out within the stated timescale."
ObjSendMail.From = "webmaster#COMPANY-NAME.com"
'ObjSendMail.CC = "someone#someone.net"
'ObjSendMail.AddAttachment "c:\myweb\somefile.jpg"
Bodytxt = "You have been assigned a FRA Task, the details are the following: " & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "UPRN: " &FireUPRN & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "FRA Date: " &FRADate & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Survey Company: " &SurveyCompany & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Assessor: " &Assessor & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Task Type: " &TaskType & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Task: " &Task & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Action Type: " &ActionType & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Priority: " &Priority & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Recommendation Date: " &RecommendationDate & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Task Allocated Date: " &TaskAllocatedDate & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Task Allocated To: " &TaskAllocatedTo & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Target Date: " &TargetDate & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Task Status: " &TaskStatus & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Task Comments: " &TaskComments & VbCrLf & VbCrLf
Bodytxt = Bodytxt & "Photo: " &Photo & VbCrLf & VbCrLf
ObjSendMail.TextBody = Bodytxt ' body text
ObjSendMail.Send 'send command
Set ObjSendMail = Nothing 'reset mail
' -------------------------
'End Custom Code
From your description, it sounds as if you are making the erroneous conclusion that if you can send to some recipients but not others, then there is something wrong with your email sending code. Think of it this way... the code above is building an email message that it is going to give to a specified SMTP server to deliver. That SMTP server is the one you specify in the second configuration field in your code (configuration/smtpserver).
The real problem you are most likely encountering has more to do with mail routing and delivery. If you are specifying from addresses for a different domain than what your mail server is setup to forward SMTP mail for, then it is either getting rejected at your mail server or one of the next SMTP servers it attempts to forward the message to either in between or at the actual destination SMTP server for the recipients inbox. Try using a plain SMTP client using the same SMTP server settings above and you will see the same results.

VBS Objshell.run not executing "%COMSPEC% /c ping " & MyObj & " >>" & ReportFileNAme

The code is supposed to execute some ping and tracert commands to a file, then email the file. Instead it creates a BLANK file.
I tried redirecting from Objshell.EXEC but the pop-ups windows that pop up are annoying and steal focus; and I want this to run periodically in the background using Task Scheduler.
The generated syntax looks like this (And works when pasted to command line):
%COMSPEC% /c ping speedtest.advance2000.com >>c:\temp\testforteresa2-foo#bar-2014-01-08__10-01.txt
The resultant command string works when pasted into a CMD> window but the tests in excel and in the executed VBS it yields a blank file...
Wouldn't mind having a wait state to check for the email to be sent so it could delete the txt file. Will figure that out later :)
'On Error Resume Next
Const ForReading = 1
Const ForAppending = 8
'PingSpeedTest
Sub PingSpeedTest()
Dim GetUserLoginID ''As String
Set objfso = CreateObject("Scripting.FileSystemObject")
Dim WSHNetwork
Set WSHNetwork = CreateObject("WScript.Network")
GetUserLoginID = CStr(WSHNetwork.UserName)
getuserdomain = CStr(WSHNetwork.UserDomain)
'''''''''''REPORT NAME''''''''''''''''''''''''''''''
ReportFileNAme = "c:\temp\testforteresa2-" & GetUserLoginID & "#" & getuserdomain & "-" & _
DatePart("yyyy", Now) & "-" & _
Right("0" & DatePart("m", Now), 2) & "-" & _
Right("0" & DatePart("d", Now), 2) & "__" & _
Right("0" & DatePart("h", Now), 2) & "-" & _
Right("0" & DatePart("m", Now), 2) & ".txt"
On Error Resume Next
objfso.DeleteFile (ReportFileNAme)
On Error GoTo 0
Set reportfile = objfso.OpenTextFile(ReportFileNAme, ForAppending, True)
Set objShell = CreateObject("WScript.Shell")
Set List = CreateObject("System.Collections.ArrayList")
List.Add "speedtest.advance2000.com"
List.Add "myphone.advance2000.com"
List.Add "vdesk.advance2000.com"
'''
For Each MyObj In List
MyCmd = "%COMSPEC% /c ping " & MyObj & " >>" & ReportFileNAme '''<<< Should work- creates correct syntax but no output
objShell.Run MyCmd, 3, True
MyCmd = "%COMSPEC% /c tracert " & MyObj & " >>" & ReportFileNAme
objShell.Run MyCmd, 3, True
Next ''MyObj
Dim olLook ''As Object 'Start MS Outlook
Dim olNewEmail ''As MailItem ' Object 'New email in Outlook
Dim strContactEmail ''As String 'Contact email address
Set olLook = CreateObject("Outlook.Application")
Set olNewEmail = olLook.createitem(0)
strEmailSubject = "TopSellers.accdb Application"
strEmailText = "PING AND TRACEROUTE RESULTS"
'strContactEmail = GetUserLoginID & "#" & getuserdomain & ".com"
With olNewEmail 'Attach template
.To = "Foo#BAR.com" 'strContactEmail<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
'.CC = strCc
.body = strEmailText
.Subject = "RE:PING AND TRACERT RESULTS"
.display
.Attachments.Add (ReportFileNAme)
End With
'objfso.DeleteFile (ReportFileNAme)
End Sub
Your
Set reportfile = objfso.OpenTextFile(ReportFileNAme, ForAppending, True)
opens the file named ReportFileNAme. The .Run
"%COMSPEC% /c ping " & MyObj & " >>" & ReportFileNAme
then asks the OS to write to that open file. Try to skip the creation of reportfile.

CDO.Message delivery notification failed

Here is my environment: Windows Server 2003, Microsoft Access 2003, Microsoft VB 6.5
Trying to send email from Access using CDO.Message. Here is the portion of my code:
Private Sub btnTestEmail_Click()
On Error GoTo SendMail_Error:
Dim Mailmsg As Object
Dim mailconf As Object
Dim McFields As Object
Dim strSchemas As String
Set Mailmsg = CreateObject("CDO.Message")
Set mailconf = CreateObject("CDO.Configuration")
Set McFields = mailconf.Fields
strSchemas = "http://schemas.microsoft.com/cdo/configuration/"
With McFields
.Item(strSchemas & "sendusing") = 2
.Item(strSchemas & "smtpserver") = "smtp.gmail.com"
.Item(strSchemas & "smtpserverport") = 465
.Item(strSchemas & "smtpauthenticate") = 1
.Item(strSchemas & "sendusername") = "my_email#gmail.com"
.Item(strSchemas & "sendpassword") = "my_gmail_password"
.Item(strSchemas & "smtpconnectiontimeout") = 60
.Item(strSchemas & "smtpusessl") = 1
.Update
End With
Set Mailmsg.Configuration = mailconf
With Mailmsg
.TextBody = "Test email body text"
.Subject = "Test email subject"
.To = "target_email#gmail.com"
.from = "my_email#gmail.com"
'.AddAttachment "D:\test.pdf"
.Fields("urn:schemas:mailheader:disposition-notification-to") = "my_email#gmail.com"
.Fields("urn:schemas:mailheader:return-receipt-to") = "my_email#gmail.com"
' Set delivery status notification (DSN)
' Name Value Description
' cdoDSNDefault 0 No DSN commands are issued.
' cdoDSNNever 1 No DSN commands are issued.
' cdoDSNFailure 2 Return a DSN if delivery fails.
' cdoDSNSuccess 4 Return a DSN if delivery succeeds.
' cdoDSNDelay 8 Return a DSN if delivery is delayed.
' cdoDSNSuccessFailOrDelay 14 Return a DSN if delivery succeeds, fails, or is
.DSNOptions = 0
.Fields.Update
.Send
End With
MsgBox "Message Sent", vbOKOnly
Set Mailmsg = Nothing
Set mailconf = Nothing
Set McFields = Nothing
Exit Sub
SendMail_Error:
MsgBox Err.Description, vbOKOnly
End Sub
With DSNOptions = 0 works great but I would like to get delivery notification (not read notification).
If I set DSNOptions to any allowed non-zero value the email doesn't even arrives to the target email and I don't get any notification to my email.
Strange thing if I set unexisting target email (on purpose) I get delivery unsuccessful notification even with DSNOptions = 0.
Am I missing something in the code? Found on multiple other web site people claims this code works but using other smtp servers. Any help appreciated.

How to replace a special character in email body with a value in each row using Excel with VBA to multiple recipients

I am creating an Excel UserForm that creates a separate email for up to 500 recipients.
There are 4 columns on the worksheet: Name(Column A), Email(Column B), Value 1(Column C).
The code uses the For and Next loop style, where r is declared as an Integer (r = 2 To 500) and with the MailItem Object, .To =Cells(r,2).
The issue I have is attempting to incorporate values from a range (Column C) that replace special characters placed in the text box used to create the body of the email.
So if I were to type, Hello, There were ^&^ transactions that failed yesterday. and hit a command button used for "Send", it would send an email to the each email address listed in Column B and replace ^&^ with the value in Column C to each individual email address (each row).
Below is the VBA code as an example. There are a lot of other declared variables that I did not mention of course to keep this inquiry as short as possible.
Dim Signature As String, EmailSensitivity As String, EmailImportance As String
Dim Greeting As String, Punctuation As String, Security As String
Sub SendButton1_Click()
If SubjectText = vbNullString Then
If EmailBody1 = vbNullString Then
MsgBox "Form Incomplete:" & vbCrLf & vbCrLf & _
"No Subject or Email Text.", vbOKOnly
Exit Sub
End If
End If
If SubjectText = vbNullString Then
MsgBox "Form Incomplete:" & vbCrLf & vbCrLf & _
"Please enter Subject.", vbOKOnly
Exit Sub
End If
If EmailBody1 = vbNullString Then
MsgBox "Form Incomplete:" & vbCrLf & vbCrLf & _
"Please enter Email Text."
Exit Sub
End If
If SignatureText1 = vbNullString Then
Continue = MsgBox("Your email contains no signature." & vbCrLf & vbCrLf & _
"Are you sure you wish to proceed?", vbYesNo)
If Continue = vbNo Then
Exit Sub
End If
End If
Dim OutApp As Object, OutMail As Object
Dim r As Integer
Application.ScreenUpdating = False
For r = 2 To 501
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(olMailItem)
On Error Resume Next
With OutMail
.Subject = Security & SubjectText.Value
.Body = EmailBody1.Value & vbCrLf & vbCrLf & _
SignatureText1.Value
.To = Cells(r, 2)
.Attachements.Add AttachmentText1.Value
.Importance = EmailImportance
.Sensitivity = EmailSensitivity
.Send
End With
Next r
Set OutApp = Nothing
Application.ScreenUpdating = True
Sheet1.Range("A2:B501").Clear
Continue = MsgBox("You have successfully generated a mass email!" & vbCrLf & vbCrLf & _
"Would you like to generate another email?", vbYesNo)
If Continue = vbNo Then
Application.Quit
End If
End Sub
I am still an amateur, so I'm working on cleaning a lot of unnecessary code, but this inquiry is mainly on replacing the special character with the value listed in each row.
This is my first time actually posting an inquiry on a forum, so please let me know if I am not following the correct procedure as your help is much appreciated.
It might be as simple as this, using the Replace function:
...
With OutMail
.Subject = Security & SubjectText.Value
.Body = Replace(EmailBody1.Value,"^&^",Cells(r, 3)) & _
vbCrLf & vbCrLf & SignatureText1.Value
...
Unrelated to this, but importat: On Error Resume Next means the sending (and any operation after that) will silently fail. This will make future debugging more difficult, frustrating and expensive. You should at least log relevant details about what error occured, and for what row in the sheet. And be sure to re-enable error-checking with on error goto 0 or similar after the part of your program that might fail unexpectedly.