Sending e-mail using VBScript through Outlook Anywhere - email

I have the unfortunate task of sending e-mail through a client that needs to connect to Outlook Anywhere through VBScript. I may not understand the correct terminology when dealing with Exchange Server, therefore the answer may be evading me simply because I don't know what I'm searching for, and after hours on Google I still haven't found the answer.
I cannot use SMTP, since the script will be connecting from many locations/networks and they may or may not block the traffic through the default port. I cannot change the default port because the network admin (who is the actual customer) will not change it.
Any pointers in the right direction will be appreciated.

If I understand your question correctly, you actually want to be able to use the installed/running version of Outlook on a client machine to generate and send an email message which it will hand off to whatever configured MTA it is using, probably via the Exchange Server it is configured to on a private LAN or over VPN when on a public network. If so, what you want to look at is using what is called "Automation" in Microsoft's nomenclature. For most scripting languages and development tools, you can do this via COM. The following Microsoft article shows how to do this in VBA which should give you enough specifics to use almost as-is for VBScript.
http://support.microsoft.com/kb/209948

The answer to my question is partially on stackoverflow already at the following question Ways to send E-Mails over MS Exchange with VBScript.
The code below (VBA, but close enough to VBScript) is simply sending a SOAP message to the Exchange Web Service. It was built from various bits and pieces found all over the web (including the links above).
Option Explicit
' ---------------------------------------------------------
' CONFIGURATION - change as needed
' ---------------------------------------------------------
Const TARGETURL = "https://mail.XXXXX.com/ews/exchange.asmx"
Const USERNAME = "XXXXX\dnreply"
Const PASSWORD = "X1X2X3X4X!x#x#x$x%"
Sub SendMessageEWS()
Dim SOAP
SOAP = CreateMessageSOAP()
' Send the SOAP request, and return the response
Dim oXMLHTTP, oXml
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
Set oXml = CreateObject("MSXML2.DOMDocument")
' Send the request
oXMLHTTP.Open "POST", TARGETURL, False, USERNAME, PASSWORD
oXMLHTTP.setRequestHeader "Content-Type", "text/xml"
oXMLHTTP.send SOAP
If oXMLHTTP.Status = "200" Then
' Get response
If oXml.LoadXML(oXMLHTTP.ResponseText) Then
' Success
Debug.Print oXml.XML
End If
Else
Debug.Print oXMLHTTP.ResponseText
MsgBox "Response status: " & oXMLHTTP.Status
End If
End Sub
Function CreateMessageSOAP()
' Normally this is done by using the DOM, but this is easier for a demo...
Dim SOAPMsg
SOAPMsg = SOAPMsg & "<?xml version='1.0' encoding='utf-8'?>"
SOAPMsg = SOAPMsg & " <soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:t='http://schemas.microsoft.com/exchange/services/2006/types' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"
SOAPMsg = SOAPMsg & " <soap:Body>"
SOAPMsg = SOAPMsg & " <CreateItem MessageDisposition='SendAndSaveCopy' xmlns='http://schemas.microsoft.com/exchange/services/2006/messages'>"
SOAPMsg = SOAPMsg & " <SavedItemFolderId>"
SOAPMsg = SOAPMsg & " <t:DistinguishedFolderId Id='sentitems' />"
SOAPMsg = SOAPMsg & " </SavedItemFolderId>"
SOAPMsg = SOAPMsg & " <Items>"
SOAPMsg = SOAPMsg & " <t:Message>"
SOAPMsg = SOAPMsg & " <t:Subject>Exchange Web Service E-Mail Test</t:Subject>"
' For HTML message body
SOAPMsg = SOAPMsg & " <t:Body BodyType='HTML'><![CDATA[<h1>Test html body</h1>]]></t:Body>"
' For text message body
' SOAPMsg = SOAPMsg & " <t:Body BodyType='Text'><![CDATA[Test text body]]></t:Body>"
SOAPMsg = SOAPMsg & " <t:ToRecipients>"
SOAPMsg = SOAPMsg & " <t:Mailbox>"
SOAPMsg = SOAPMsg & " <t:EmailAddress>recipient#XXXXX.com</t:EmailAddress>"
SOAPMsg = SOAPMsg & " </t:Mailbox>"
SOAPMsg = SOAPMsg & " </t:ToRecipients>"
SOAPMsg = SOAPMsg & " </t:Message>"
SOAPMsg = SOAPMsg & " </Items>"
SOAPMsg = SOAPMsg & " </CreateItem>"
SOAPMsg = SOAPMsg & " </soap:Body>"
SOAPMsg = SOAPMsg & " </soap:Envelope>"
CreateMessageSOAP = SOAPMsg
End Function

Related

Calling REST API from Visual Basic

I keep getting a 404 error.
It works fine if I call the REST API from SoapUI.
I’m using Visual Basic VS2015.
I have a sample function which I’m calling from a simple forms project. This is just to get the REST API to work. The REST API call will go into a Visual Basic Windows Service once I get it working,
There is a form named form1 which has a txtURL textbox, a button to call sub Main(), and an output textbox called textbox1.
Public Shared Sub Main()
Try
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(Form1.txtURL.Text), HttpWebRequest)
With myHttpWebRequest
.Method = "POST"
.ContentType = "application/json"
.Accept = "application/json"
.MediaType = "jsonp"
With .Headers
.Add("Authorization", "Bearer ABCDabcd1234=")
.Add("riskLevelStatus", "6897")
.Add("userId", "12345")
.Add("applicationName", "MyApp")
End With
End With
Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
Form1.TextBox1.Text = Form1.TextBox1.Text & myHttpWebResponse.ToString() & vbCrLf
myHttpWebResponse.Close()
'Catch exception if trying to add a restricted header.
Catch e As ArgumentException
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-ArgumentException: " & e.Message & vbCrLf
Catch e As WebException
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-WebException: " & e.Message & vbCrLf
If e.Status = WebExceptionStatus.ProtocolError Then
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-Status Code: " & CType(e.Response, HttpWebResponse).StatusCode & vbCrLf
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-Status Description: " & CType(e.Response, HttpWebResponse).StatusDescription & vbCrLf
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-Server: " & CType(e.Response, HttpWebResponse).Server & vbCrLf
End If
Catch e As Exception
Form1.TextBox1.Text = Form1.TextBox1.Text & "Error-Exception: " & e.Message & vbCrLf
End Try
End Sub 'Main
Here is what is outputted to textbox1:
Error -WebException: The remote server returned an Error: (400) Bad Request.
Error -Status Code: 400
Error -Status Description
Error -Server
What should be returned is a single line JSON, similar to this:
{“quid”: “jhgdsjdshg-hdbw-akjhjk-kdhbfsihg”}
It works fine when calling from SoapUI.
I believe this issue is how do I add data to the body?
I figured it out. I cannot believe nobody had an answer.
Public Sub Try01(URL)
Try
Dim myReq As HttpWebRequest
Dim myResp As HttpWebResponse
Dim myReader As StreamReader
myReq = HttpWebRequest.Create(URL)
myReq.Method = "POST"
myReq.ContentType = "application/json"
myReq.Accept = "application/json"
myReq.Headers.Add("Authorization", "Bearer LKJLMLKJLHLMKLJLM839800K=")
Dim myData As String = "{""riskLevelStatus"":""0001"",""userId"":""10000004030"",""applicationName"":""MyTestRESTAPI""}"
myReq.GetRequestStream.Write(System.Text.Encoding.UTF8.GetBytes(myData), 0, System.Text.Encoding.UTF8.GetBytes(myData).Count)
myResp = myReq.GetResponse
myReader = New System.IO.StreamReader(myResp.GetResponseStream)
TextBox1.Text = myReader.ReadToEnd
Catch ex As Exception
TextBox1.Text = TextBox1.Text & "Error: " & ex.Message
End Try
End Sub

Send email with attachment from any email program

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.

ASP Contact form error Server object error 'ASP 0177 : 800401f3'

One of my websites contact/reservations form has suddenly stopped working and I now receive the following error.
Server object error 'ASP 0177 : 800401f3'
Server.CreateObject Failed
/contact2.asp, line 51
I've done a bit of research and it seems to relate to classic ASP commands but
my knowledge of ASP is limited.
Here is the full code:-
<%
name = request.form("name")
email = request.form("email")
phone = request.form("phone")
guests = request.form("guests")
datum2 = request.form("datum2")
info = request.form("info")
time_hour = request.form.item("time_hour")
time_minute = request.form.item("time_minute")
moda_event = request.form.item("modaEvent")
sign_up = request.form.item("signup")
If name="" or email="" Then
url = "reservations.asp?reqd=* indicates required field&name=" & mname & "&email=" & memail
If name="" Then
url = url & "&mname=*"
End if
If email="" Then
url = url & "&memail=*"
End if
response.redirect url & "&foobar=foobar#form"
response.end
End if
Dim objCDONTS ' Email object
Dim strFromName ' From persons' real name
Dim strFromEmail, strToEmail ' Email addresses
Dim strSubject, strName, strPhone, strEmail, strGuests, strDate, strHour, strMinute, strEvent, strInfo, strSignup 'Message
Dim misccompo
strSubject = "Reservation Form"
strFromName = Trim(Request.Form("name"))
strFromEmail = Trim(Request.Form("email"))
strToEmail = "reservations#modarestaurant.co.uk"
strName = Trim(Request.Form("name"))
strPhone = Trim(Request.Form("phone"))
strEmail = Trim(Request.Form("email"))
strGuests = Trim(Request.Form("guests"))
strDate = Trim(Request.Form("datum2"))
strHour = Trim(Request.Form.Item("time_hour"))
strMinute = Trim(Request.Form.Item("time_minute"))
strEvent = Trim(Request.Form.Item("moda_event"))
strInfo = Trim(Request.Form("info"))
strSignup = Trim(Request.Form.Item("signup"))
Set objCDONTS = Server.CreateObject("CDONTS.NewMail")
objCDONTS.From = strFromName & " <" & strFromEmail & ">"
objCDONTS.To = strToEmail
objCDONTS.Subject = strSubject
objCDONTS.Body = "--------------------------------------" & vbcrlf & vbcrlf & "Name: " & strName & vbcrlf & "Contact Number: " & strPhone & vbcrlf & "Email Address: " & strEmail & vbcrlf & "No. of Guests: " & strGuests & vbcrlf & "Date: " & strDate & vbcrlf & "Time: " & strHour & ":" & strMinute & vbcrlf & "Event: " & strEvent & vbcrlf & "Additional Info: " & vbcrlf & strInfo & vbcrlf & "Newsletter Signup: " & strSignup &vbcrlf & "--------------------------------------------------------------" & vbcrlf & "MESSAGE ENDS: End of info"
objCDONTS.Send
Set objCDONTS = Nothing
response.redirect "thank-you.asp"
response.end
%>
The line 51 error is this line;
Set objCDONTS = Server.CreateObject("CDONTS.NewMail")
Any help would be greatly appreciated.
The error
Server object error 'ASP 0177 : 800401f3'
Server.CreateObject Failed
/contact2.asp, line 51
means that the object could not be created because it could not find the appropriate DLL for the object requested. In other words, it is looking for the CDONTS COM component that was included with NT SP4 as the file cdont.dll. CDONTS was deprecated in Windows 2000 and completely removed in Windows 2003. Therefore, if you are using Window 2003, Windows 2008 or Windows 2012 server this error makes sense since the DLL is not present.
To fix this problem try the following - use CDOSYS. CDOSYS (cdosys.dll) is a library file provided as part of IIS for Windows 2000, Windows 2003 Server, and Windows 2008 Server. This DLL enabled applications to route SMTP messages across multiple platforms and added much more functionality over the older CDONTS library.
Here is a greatly simplified example to model some changes on
Dim Message As New CDO.Message
sch = "http://schemas.microsoft.com/cdo/configuration/"
Set cdoConfig = CreateObject("CDO.Configuration")
with cdoConfig.Fields
.item(sch & "sendusing") = 2
.Item(sch & "smtpserver") = "mail.xxxx.com" ' your SMTP mail server
.Item(sch & "smtpserverport") = 2525
.update
end with
'Create CDO message object
Set Message = CreateObject("CDO.Message")
With Message
set .configuration = cdoConfig
'Set email adress, subject And body
.From = strFromName
.To = strToEmail
.Subject = strSubject
.TextBody = TextBody
'Send the message
.Send
End With

How to check is myMail.Send is true/false

<%
Dim sent
Dim YourName
Dim YourEmail
Dim YourMessage
Set myMail2=CreateObject("CDO.Message")
YourName = Trim(Request.Form("Name"))
YourEmail = Trim(Request.Form("Email"))
YourMessage = Trim(Request.Form("Message"))
Dim Body
Dim body2
Body = Body & "Their Name: " & VbCrLf & YourName & VbCrLf & VbCrLf
Body = Body & "Their Email: " & VbCrLf & YourEmail & VbCrLf & VbCrLf
Body = Body & "Their Message: " & VbCrLf & YourMessage & VbCrLf & VbCrLf
Set myMail=CreateObject("CDO.Message")
myMail.Subject="A New Enquiry!"
myMail.From="admin#musicalmatters.co.uk"
myMail.To="james#devine.eu"
myMail.TextBody=Body
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.1and1.com"
'Server port
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
myMail.Configuration.Fields.Update
myMail.Send
set myMail=nothing
body2="Thank you for contacting us!" & VbCrLf & "This is just a brief message to let you know your form was submitted successfully!"& VbCrLf & VbCrLf & "You may reply to this address, but you may not necessarily receive a reply, "& "you should receive a reply in 1-2 business day(s)!"& VbCrLf & "Thank you very much,"& VbCrLf & VbCrLf & "Musical Matters."& VbCrLf & "admin#musicalmatters.co.uk"
Set myMail2=CreateObject("CDO.Message")
myMail2.Subject="Thanks for Contacting Us!"
myMail2.From="admin#musicalmatters.co.uk"
myMail2.To=YourEmail
myMail2.TextBody=body2
myMail2.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
myMail2.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.1and1.com"
'Server port
myMail2.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
myMail2.Configuration.Fields.Update
myMail2.Send
If myMail2.Send="" Then
Response.Redirect("http://www.musicalmatters.co.uk/success.htm")
set myMail2=nothing
Else
Response.Redirect("http://www.musicalmatters.co.uk/error.htm")
set myMail2=nothing
End If
The problem with my asp script is that I need to check whether the emails were sent or not and redirect them to an error or success page depending on the result.
If myMail2.Send="" Then
Response.Redirect("http://www.musicalmatters.co.uk/success.htm")
set myMail2=nothing
Else
Response.Redirect("http://www.musicalmatters.co.uk/error.htm")
set myMail2=nothing
End If
in the code above mymail2.Send="" because i was testing something, i know i have to change the value to true or false, please be hasty with your answers!
Thanks in advance!
If the email address has valid syntax and the SMTP server is up and running, the Send method will never throw error, even if the email address does not exist.
There is no way to know 100% if the email reached its destination - one thing I can think is to check (using FSO) the BadMail and Queue folders in the SMTP root after few seconds from sending, and if they contain new entry it means something went wrong.
However as you're using external mail service, you'll have to contact them and ask for a way to get notified somehow when the delivery fails.
Seems to require using On Error statement.
On Error Resume Next
myMail2.Send
If Err.Number = 0 Then
set myMail2 = Nothing
Response.Redirect("http://www.musicalmatters.co.uk/success.htm")
Else
set myMail2 = Nothing
Response.Redirect("http://www.musicalmatters.co.uk/error.htm")
End If

400 Bad Request : Consuming WCF basicHttpBinding (Soap) using JScript/VBScript

var oXMLDoc, oXMLHttp, soapRequest, soapResponse;
oXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
oXMLHttp.open("POST", "http://nerdbox/HelloService.svc", false);
// Add HTTP headers
oXMLHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
oXMLHttp.setRequestHeader("SOAPAction", "http://tempuri.org/IHelloService/SayHello");
// Form the message
soapRequest = '<?xml version="1.0" encoding="utf-16"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><SayHello xmlns="http://tempuri.org/"><name>Zuhaib</name></SayHello></soap:Body></soap:Envelope>';
WScript.Echo("Request : " + soapRequest);
oXMLHttp.send(soapRequest);
soapResponse = oXMLHttp.responseXML.xml;
WScript.Echo("Respose : " + soapResponse);
Whats wrong with this JScript? why am I getting 400 Bad Request. I read similar threads in stackoverflow .. some say its soap message formatting problem.
This is what the message looks like if I take it from fiddler.
Try changing your action from IHelloService to HelloService.
And let me ask you, why are you doing it the hard way. Just add a webHttpBinding and use JSON.
See a very easy example here.
I had to change your code to the following to get it to run in VBSEdit...then I (obviously) got the error about it not being able to find the resource...but change your code to this and see if it makes a difference?
Dim oXMLDoc, oXMLHttp, soapRequest, soapResponse
Set oXMLHttp = CreateObject("Microsoft.XMLHTTP")
oXMLHttp.open "POST", "http://nerdbox/HelloService.svc", False
'// Add HTTP headers
oXMLHttp.setRequestHeader "Content-Type", "text/xml; charset=utf-8"
oXMLHttp.setRequestHeader "SOAPAction", "http://tempuri.org/IHelloService/SayHello"
'// Form the message
soapRequest = "<?xml version=""1.0"" encoding=""utf-16""?><soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><soap:Body><SayHello xmlns=""http://tempuri.org/""><name>Zuhaib</name></SayHello></soap:Body></soap:Envelope>"
WScript.Echo "Request : " + soapRequest
oXMLHttp.send soapRequest
soapResponse = oXMLHttp.responseXML.xml
WScript.Echo "Respose : " + soapResponse