Sending emails using VBScript

To do so, follow the sample code shown below. To use the code as-is, just alter the configuration parameters by providing the from address, to address, subject, body, and SMTP server information. Optionally, you may also provide a path to a file that you want to attach to the email. Usually SMTP port number is 25; if you are unsure, leave this parameter untouched and it will probably work at the default value of 25.

option explicit

dim fromAddress, toAddress, subj, body, smtp, attach, smtpPort

'''''''''''''''''
' Configuration '
'''''''''''''''''

' Required parameters
fromAddress = "my@email.address"      ' The from email address
toAddress = "recepient@email.address" ' The to email address
subj = "Email Subject"                ' The subject of the email
body = "Put a message here!"          ' The body message of the email
smtp = "mail.server.com"              ' Name of the SMTP server you wish to use

' Optional parameters
attach = "c:filename.txt"            ' Optional file you may wish to attach to the email
smtpPort = 25                         ' SMTP port used by your server, usually 25; if not provided, the script will default to 25

'''''''''''''''''''''
' End Configuration '
'''''''''''''''''''''


if fromAddress = "" then
	msgbox("Error: From email address not defined")
elseif toAddress = "" then
	msgbox("Error: To email address not defined")
elseif subj = "" then
	msgbox("Error: Subject not defined")
elseif body = "" then
	msgbox("Error: Body not defined")
elseif smtp = "" then
	msgbox("Error: SMTP server not defined")
else
	dim objMessage
	Set objMessage = CreateObject("CDO.Message")
	objMessage.Subject = subj
	objMessage.From = fromAddress
	objMessage.To = toAddress
	objMessage.TextBody = body
	if attach <> "" then
		objMessage.AddAttachment attach
	end if
	
	objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
	objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtp
	if smtpPort <> "" then
		objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = smtpPort
	else
		objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
	end if
	objMessage.Configuration.Fields.Update
	
	objMessage.Send
	
	msgbox("Email sent successfully")
end if

Leave a Reply

Your email address will not be published.