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


  • 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


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"
 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
        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)
   If Not myRecipient.Resolved Then
      MsgBox sRecipient + "is an Unknown recipient"
      bCanSend = true
   End If
 if bCanSend Then
   newMail.Attachments.Add(sLogfile).Displayname = "Attachment"
 End If

 Set ol = Nothing
 Set olTest = Nothing

end if




cscript outlooksendfile.vbs myresume.txt ";;" "My Resume"