Software >> Applications >> Microsoft Office >> VBA >> Outlook >> Examples >> Create and send email with a file attachment

Assumptions

  • Outlook application is currently running and connected at the time the script was run or
  • Outlook profile named "myprofile" have been defined on the machine where the script is being run and the profile will launch outlook and with saved logon password

 outlooksendfile.vbs

On Error Resume Next
Dim olProfile
Dim sSubject,sRecipients,sLogfile
Dim sMessageBody
Dim MessageAttachment1
Dim ol, ns, newMail

Set oArgs = Wscript.Arguments
If oArgs.Count < 2 Then
    wscript.echo "Syntax: outlooksendfile.vbs filename recipients subject"
else
 sLogfile           = oArgs(0)
 sRecipients        = oArgs(1)
 sSubject           = oArgs(2)

 olProfile          = "myprofile"

 sMessageBody       = "Please find attached" & vbCrLf & vbCrLf

 Set olTest = GetObject(,"Outlook.Application")

 If Err.Number = 0 Then
        Wscript.Echo "Outlook is running ... " & vbCrLf
 Else
        Wscript.Echo "Outlook is not running, launching outlook first ..." & vbCrLf & vbCrLf & "See Attached"
        Set oShell = CreateObject("WScript.Shell")
        oShell.Run "Outlook.Exe /profile " & olProfile
        WScript.Sleep 30000
 End If

 Wscript.Echo "Getting Outlook app object ..." & vbCrLf   
 Set ol = GetObject(,"Outlook.Application")
 Set ns = ol.getNamespace("MAPI")

 Set newMail = ol.CreateItem(olMailItem)
 newMail.Subject = sSubject
 newMail.Body    = sMessageBody & vbCrLf
 
 bCanSend = false
 aRecipients = Split(sRecipients,";")
 for each sRecipient in aRecipients
   Set myRecipient = ns.CreateRecipient(sRecipient)
   myRecipient.Resolve
   If Not myRecipient.Resolved Then
      MsgBox sRecipient + "is an Unknown recipient"
   Else
      newMail.Recipients.Add(sRecipient)
      bCanSend = true
   End If
 next
 if bCanSend Then
   newMail.Attachments.Add(sLogfile).Displayname = "Attachment"
   newMail.Send
 End If

 Set ol = Nothing
 Set olTest = Nothing

end if

 

 

Example

cscript outlooksendfile.vbs myresume.txt "tom@example.com;dick@example.com;harry@example.com" "My Resume"