Can i send a mail with attachment from excel
Yes, you can send an email with an attachment from Excel using VBA (Visual Basic for Applications). Here's a step-by-step guide:
Prerequisites:
- You need to have Excel 2007 or later version.
- You need to have Outlook installed on your computer.
Steps:
-
Open your Excel workbook and go to the Visual Basic Editor by pressing
Alt + F11
or by navigating toDeveloper
tab >Visual Basic
button. -
In the Visual Basic Editor, click
Insert
>Module
to insert a new module. -
Paste the following code into the module:
Sub SendEmailWithAttachment() Dim olApp As Object Dim olMail As Object Dim filePath As String ' Set the file path and name of the attachment filePath = "C:\Path\To\Your\File.xlsx" ' Create a new Outlook application object Set olApp = CreateObject("Outlook.Application") ' Create a new email object Set olMail = olApp.CreateItem(0) ' Set the email properties With olMail .To = "[email protected]" .Subject = "Email with attachment" .Body = "This is the email body" ' Add the attachment .Attachments.Add filePath ' Send the email .Send End With ' Clean up Set olMail = Nothing Set olApp = Nothing End Sub
-
Replace
"C:\Path\To\Your\File.xlsx"
with the actual file path and name of the attachment you want to send. -
Replace
"[email protected]"
with the actual email address of the recipient. -
Replace
"This is the email body"
with the actual email body you want to send. -
Save the module by clicking
File
>Save
(or pressCtrl + S
). -
To run the macro, go back to your Excel workbook and press
Alt + F8
to open the Macro dialog box. Select theSendEmailWithAttachment
macro and clickRun
.
Tips:
- Make sure to adjust the file path and name to match the actual location and name of your attachment.
- You can also use the
GetSaveAsFilename
method to prompt the user to select a file to attach. - You can customize the email properties (e.g., subject, body, recipient) as needed.
- This code uses late binding, which means you don't need to set a reference to the Outlook library. However, if you prefer to use early binding, you can set a reference to the Outlook library and use the
Outlook.Application
andOutlook.MailItem
objects directly.