|
|
|
|
|
|
Multiple Apps
|
Automating Outlook to Send an Email with an Attachment
|
|
Ease of Use
|
Intermediate
|
Version tested with
|
2000,2002,2003
|
Submitted by:
|
mark007
|
Description:
|
This code will automate Outlook to create a new email with the given attachment.
|
Discussion:
|
The following code can be used to automate Outlook from Excel, Word, Access or any VBA enabled application. It could also be used in a VB6 app. It will create a new mail message and attach the file specified. In it's current form it will display this message for you to check before hitting send, however it can easily be modified as suggested in the code to send it straight away.
|
Code:
|
instructions for use
|
Option Explicit
Sub SendMail()
Dim olApp As Outlook.Application
Dim olMail As Outlook.MailItem
Dim blRunning As boolean
blRunning=True
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If olApp Is Nothing Then
Set olApp = New Outlook.Application
blRunning=False
End If
On Error Goto 0
Set olMail = olApp.CreateItem(olMailItem)
With olMail
.Subject = "My email with attachment"
.Recipients.Add "name@host.com"
.Attachments.Add "c:\test.txt"
.Body = "Here is an email"
.Display
End With
If Not blRunning Then olApp.Quit
Set olApp=Nothing
Set olMail=Nothing
End Sub
|
How to use:
|
- Open you application of choice (e.g. Excel or Word)
- Hit Alt + F11 to open the Visual Basic Editor.
- Click Insert-Module from the menu.
- Goto Tools-References and place a checkbox next to Microsoft Outlook xx.0 Object Library
- Copy the above code
- Paste the code into the window that appears at right of the Visual Basic Editor
- Edit the code to specify the path of the file to attach, subject, recipients etc.
- Close the VBE (Alt + Q or press the x in the top right corner).
|
Test the code:
|
- Run the macro via Tools-Macros-Macros, selecting it and hitting run or call the procedure through code
|
Sample File:
|
sample.zip 6KB
|
Approved by MOS MASTER
|
This entry has been viewed 190 times.
|
|