Attach a file to an email with VBScript

January 19th, 2006

A VBScript that sends an email with a file attachment.   I’ve used this in Windows 2000 (Win2K) and Windows XP Pro (XP Pro) environments.eg. Drag a file from explorer onto the icon for this script and it will send that file as an attachment to the email address you specify.

eg. Or.. incorporate it into an automated process by passing the filename and email address as parameters. This is useful if you want to send a file with a scheduled task or job.

Dim oArgs, i, sSubject, sBody, sEmail
Dim fromEmail, fileName, toEmail, smtpServer
 

smtpServer = ""
fromEmail = "Daemon@domain.com"

Set oArgs = WScript.Arguments

If oArgs.Count < 1 Then
     WScript.Echo "Drag a file onto this icon to email it." & vbcrlf & vbcrlf & "You will be prompted for an email address to send to."
     WScript.Quit
End If

fileName = oArgs(0)

If oArgs.Count <> 2 Then
     toEmail = InputBox(”Please type in the recipient’s email:”, “Send to?”, “;@domain.com”)
Else
     toEmail = oArgs(1)
End If

if fileName <> “” and fromEmail <> “” and toEmail <> “” then

     sSubject = “File from [” & fromEmail & “]”
     sBody = “See attached file [” & GetFilenameOnly(fileName) & “]”
     sEmail = toEmail
     
     MailMe_CDOSys sSubject, sBody, sEmail, fileName
     If oArgs.Count <> 2 Then WScript.Echo “Mail sent…”

else
     If oArgs.Count <> 2 Then WScript.Echo “Incorrect parameters.. no email sent”

end if

Sub MailMe_CDOSYS (s, b, email, attachment)
     On Error Resume Next
     Dim o
     Set o = CreateObject(”CDO.Message”)
     o.From = fromEmail
     o.Sender = “MailMeAttachment”
     o.To = email
     o.Subject = s
     o.AddAttachment fileName
     o.TextBody = b
     o.DNSOptions = 0
     o.ConfigurationFields(”http://schemas.microsoft.com/cdo/configuration/smtpserver”).Value = smtpServer
     o.ConfigurationFields(”http://schemas.microsoft.com/cdo/configuration/sendusing”).Value = 2     ’send using network
     o.ConfigurationFields(”http://schemas.microsoft.com/cdo/configuration/SMTPConnectionTimeout”).Value = 30
     o.ConfigurationFields(”http://schemas.microsoft.com/cdo/configuration/SMTPServerPort”).Value = 25
     o.ConfigurationFields(”http://schemas.microsoft.com/cdo/configuration/SMTPAuthenticate”).Value = 0
     o.Configuration.Fields.Update
     o.Fields.Update
     o.send
     Set o = Nothing
End Sub

Function GetFilenameOnly(s)
     Dim sRet, iLast
     iLast = InStrRev(s, “\”)
     sRet = Right(s, len(s)-iLast)
     GetFilenameOnly = sRet
End Function

Entry Filed under: Programming

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Software

SEOElite_Box.jpg
SEO Software
keyword_elite_big.jpg
Keyword Software

More Info


Most Recent Posts