Search the Site


bottom corner

Sending emails using VBScript

Sample code provided in this article demonstrates how you can send an email, optionally with an attachment, using VBScript.

This page is filed under keyword(s): 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 = ""              ' 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")
	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 ("") = 2
	objMessage.Configuration.Fields.Item ("") = smtp
	if smtpPort <> "" then
		objMessage.Configuration.Fields.Item ("") = smtpPort
		objMessage.Configuration.Fields.Item ("") = 25
	end if
	msgbox("Email sent successfully")
end if

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): vbscript.
Author: C. Peter Chen
Last updated: 7 Aug 2008

bottom corner