Vba send mail
A popular topic!
In VBA, you can send an email using the Outlook
object library. Here's a basic example:
Step 1: Enable the Outlook Object Library
In the Visual Basic Editor (VBE), go to Tools > References and check if "Microsoft Outlook XX.X Object Library" is listed. If not, click Browse and navigate to the Outlook installation directory (e.g., C:\Program Files\Microsoft Office\OfficeXX\OUTLOOK.DLL
) and select it.
Step 2: Create an Outlook Application Object
In your VBA code, create an instance of the Outlook.Application
object:
Dim olApp As New Outlook.Application
Step 3: Create a New Email
Create a new email using the CreateItem
method:
Dim olMail As Outlook.MailItem
Set olMail = olApp.CreateItem(olMailItem)
Step 4: Set Email Properties
Set the email properties, such as subject, body, and recipients:
olMail.Subject = "Test Email"
olMail.Body = "This is a test email sent from VBA."
olMail.To = "[email protected]"
Step 5: Send the Email
Send the email using the Send
method:
olMail.Send
Full Code Example
Here's the complete code:
Sub SendEmail()
Dim olApp As New Outlook.Application
Dim olMail As Outlook.MailItem
Set olMail = olApp.CreateItem(olMailItem)
olMail.Subject = "Test Email"
olMail.Body = "This is a test email sent from VBA."
olMail.To = "[email protected]"
olMail.Send
Set olMail = Nothing
Set olApp = Nothing
End Sub
Tips and Variations
- You can also use the
CreateItem
method witholReportItem
to create a new meeting request or appointment. - To send an email with attachments, use the
Attachments.Add
method:olMail.Attachments.Add "C:\Path\To\Attachment.txt"
- To send an email with HTML formatting, use the
HTMLBody
property:olMail.HTMLBody = "<html><body>This is an HTML email.</body></html>"
- You can also use the
Outlook.MailItem.SendUsing
method to specify the email account to use for sending the email.
Remember to adjust the code to fit your specific needs and requirements. Happy coding!