I have written this very simple code to attach a file in my email, but the email comes without an attachment.
It doesn't even throw any error. I have made sure that the path is correct and the file exists.
Please help
Private Sub CommandButton2_Click()
On Error GoTo ErrHandler
' SET Outlook APPLICATION OBJECT.
Dim objOutlook As Object
Set objOutlook = CreateObject("Outlook.Application")
Dim Source_File As String
' CREATE EMAIL OBJECT.
Dim objEmail As Object
Set objEmail = objOutlook.CreateItem(olMailItem)
With objEmail
.To = "arushi.agarwal#in.ab-inbev.com"
.Subject = "This is a test message k"
.Body = "Please use this template for your weekly meeting today"
.Send ' SEND MESSAGE.
.AddAttachment ("C:\Claims\Try.docx")
End With
' CLEAR.
Set objEmail = Nothing: Set objOutlook = Nothing
ErrHandler:
'
End Sub
I have made minor changes in your code and it works for me. You also need to attach the file before sending the email (e.g. .attachment before .send)
Private Sub CommandButton2_Click()
On Error GoTo ErrHandler
' SET Outlook APPLICATION OBJECT.
Dim objOutlook As Object
Set objOutlook = CreateObject("Outlook.Application")
Dim Source_File As String
' CREATE EMAIL OBJECT.
Dim objEmail As Object
Set objEmail = objOutlook.CreateItem(olMailItem)
With objEmail
.To = "arushi.agarwal#in.ab-inbev.com"
.Subject = "This is a test message k"
.Body = "Please use this template for your weekly meeting today"
.Attachments.Add ("C:\Claims\Try.docx")
.Send ' SEND MESSAGE.
'.AddAttachment ("C:\Claims\Try.docx")
End With
' CLEAR.
Set objEmail = Nothing: Set objOutlook = Nothing
Exit Sub
ErrHandler:
Range("A1").Value = Err.Description
End Sub
Related
I want to send stakeholders an e-mail when a subordinate makes any updates in the Excel worksheet. I hope to use a Workbook_BeforeSave event where an e-mail is triggered from the subordinate's Outlook account.
The subordinate/user needs Outlook configured/installed in their system. If not mail wont be triggered.
Is there any way to overcome this, like sending the mail triggering request to a remote computer/server where Outlook is preconfigured and sending the mail from that computer/server to the stakeholder using a common or centralized Email id?
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim OutApp As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Recipient
Dim Recipients As Recipients
Set OutApp = CreateObject("Outlook.Application")
Set objOutlookMsg = OutApp.CreateItem(olMailItem)
Set Recipients = objOutlookMsg.Recipients
Set objOutlookRecip = Recipients.Add("receiver#domain.com")
objOutlookRecip.Type = 1
objOutlookMsg.SentOnBehalfOfName = "sender#domain.com"
objOutlookMsg.Subject = "Testing this macro"
objOutlookMsg.HTMLBody = "Testing this macro "
For Each objOutlookRecip In objOutlookMsg.Recipients
objOutlookRecip.Resolve
Next
objOutlookMsg.Display
objOutlookMsg.Send
Set OutApp = Nothing
End Sub
Option Explicit
Private Sub CommandButton1_Click()
On Error GoTo ErrHandler
' SET Outlook APPLICATION OBJECT.
Dim objOutlook As Object
Set objOutlook = CreateObject("Outlook.Application")
' CREATE EMAIL OBJECT.
Dim objEmail As Object
Set objEmail = objOutlook.CreateItem(olMailItem)
With objEmail
.to = "webadmin#encodedna.com"
.Subject = "This is a test message from Arun Banik"
.Body = "Hi there"
.Display ' DISPLAY MESSAGE.
End With
' CLEAR.
Set objEmail = Nothing: Set objOutlook = Nothing
ErrHandler:
'
End Sub
All you need to do is change the .Display property with .Send property.
With objEmail
.to = "arunbanik21#rediffmail.com"
.Subject = "This is a test message from Arun"
.Body = "Hi there"
.Send ' SEND THE MESSAGE.
End With
For more please check here, https://www.encodedna.com/excel/send-email-from-excel-using-vba-and-outlook.htm
Follow the steps,
We need to send emails from Outlook. Since Outlook is an outside object first thing we need to do is to set the object reference to “Microsoft Outlook 16.0 Object Library”.
In VBA, Go to Tools > References.
Now we will see the object reference library. In this window, we need to set the reference to “Microsoft Outlook 16.0 Object Library.”
After setting the object reference, click on, Ok.
Now we can access Outlook object in VBA coding
Sub SendEmail_Example1()
Dim EmailApp As Outlook.Application 'To refer to outlook application
Set EmailApp = New Outlook.Application 'To launch outlook application
Dim EmailItem As Outlook.MailItem 'To refer new outlook email
Set EmailItem = EmailApp.CreateItem(olMailItem) 'To launch new outlook
email
EmailItem.To = "Hi#gmail.com"
EmailItem.CC = "hello#gmail.com"
EmailItem.Subject = "Test Email From Excel VBA"
EmailItem.HTMLBody = "Hi," & vbNewLine & vbNewLine & "This is my first email from Excel" & _
vbNewLine & vbNewLine & _
"Regards," & vbNewLine & _
"VBA Coder" 'VbNewLine is the VBA Constant to insert a new line
EmailItem.Send
End Sub
For more, can you please give a try as mentioned in this article,
https://www.wallstreetmojo.com/vba-send-email-from-excel/
I have code for doing several tasks and would like to receive an email notification on any error. My current code works fine but I have noticed that sometimes I get 2 or 3 messages. Why it is happening so and how to fix it?
Sub PerformAll()
On Error GoTo ErrorHandler
Call RefreshQuery
Call FormatAllCells
Call BuildListWithClass
Exit Sub
ErrorHandler:
If Err <> 0 Then
Dim objOutlook As Object
Set objOutlook = CreateObject("Outlook.Application")
' CREATE EMAIL OBJECT.
Dim objEmail As Object
Set objEmail = objOutlook.CreateItem(olMailItem)
With objEmail
.To = "me.you#company.com"
.Subject = "There was an error with Importer"
.Body = "Hello Sir, there was an error with Importer. Please take a look!"
.Send
End With
' CLEAR.
Set objEmail = Nothing
Set objOutlook = Nothing
End If
Resume Next
End Sub
Looks like removing Resume Next did the job
Current code:
Sub PerformAll()
On Error GoTo ErrorHandler
Call RefreshQuery
Call FormatAllCells
Call BuildListWithClass
Exit Sub
ErrorHandler:
If Err <> 0 Then
Dim objOutlook As Object
Set objOutlook = CreateObject("Outlook.Application")
' CREATE EMAIL OBJECT.
Dim objEmail As Object
Set objEmail = objOutlook.CreateItem(olMailItem)
With objEmail
.To = "me.you#company.com"
.Subject = "There was an error with Importer"
.Body = "Hello Sir, there was an error with Importer. Please take a look!"
.Send
End With
' CLEAR.
Set objEmail = Nothing
Set objOutlook = Nothing
End If
End Sub
I have code that sends emails using the default Outlook account.
I tried changing the code to send from a specific email. When I run the macro, nothing happens.
Is something wrong with the code, or is it not working due to another issue (with Outlook and the accounts/permissions associated with it)?
Sub CommandButton1_Click()
Dim wb As Workbook
Dim olApp As Outlook.Application
Dim olMail As Outlook.MailItem
Dim q As Long
Dim oAccount As Outlook.Account
Set wb = ThisWorkbook
For Each oAccount In Outlook.Application.Session.Accounts
If oAccount = "theEmailiWantToUse#domain.com" Then
For q = 2 To 3 'LastRow
eName = wb.Sheets(1).Cells(q, 2).Value
Set olApp = New Outlook.Application
Set olMail = olApp.CreateItem(olMailItem)
mailBody = "Hello, "
With olMail
.To = Worksheets("Emails").Cells(q, 4).Value
.Subject = eName
.HTMLBody = "<!DOCTYPE html><html><head><style>"
.HTMLBody = .HTMLBody & "body{font-family: Calibri, ""Times New Roman"", sans-serif; font-size: 14px}"
.HTMLBody = .HTMLBody & "</style></head><body>"
.HTMLBody = .HTMLBody & mailBody & "</body></html>"
Set .SendUsingAccount = oAccount
.Display
' .Send
End With
Next
Else
End If
Next
Set olMail = Nothing
Set olApp = Nothing
End Sub
I know I have access to the email I would like to send emails from, as I can select it from Outlook and it works.
Add this line within the olMail
.SentOnBehalfOfName = "youraddress" 'here change this
please use this routine to find Account number of sender .
Sub Which_Account_Number()
'Don't forget to set a reference to Outlook in the VBA editor
Dim OutApp As Outlook.Application
Dim I As Long
Set OutApp = CreateObject("Outlook.Application")
For I = 1 To OutApp.Session.Accounts.Count
MsgBox OutApp.Session.Accounts.Item(I) & " : This is account number " & I
Next I
End Sub
Then
.SendUsingAccount = olApp.Session.Accounts.Item(5)' whatever account index number you want to send. i have chosen 5
instead of
Set .SendUsingAccount = oAccount
This method works for me . You can further integrate this concept in your programme. Please ensure Reference to Outlook Object Library is set in Tools/References.
An Outlook email is generated whenever I execute a VBA code in Excel. It does not automatically send, nor do I want it to. The email is populated by cell values in a range (which are based off of the ActiveCell) and I want to programmatically capture when the email is manually sent into ActiveCell.Offset(0, 13), preferably with VBA in my current Excel program.
This is the code by which I display the email:
'Send Stock Request:
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(olMailItem)
With OutMail
.BodyFormat = olFormatHTML
.HTMLBody = "My eMail's HTML Body"
.To = "myrecipients#theiremails.com"
.CC = ""
.BCC = ""
.Subject = "Stock Request"
.Display
End With
Set OutMail = Nothing
Set OutApp = Nothing
It can be done through VBA, but code below must be pasted in Outlook module instead of Excel, in Outlook=>ThisOutlookSession module. Also, make sure you allow macros in Outlook.
Private Sub Application_ItemSend(ByVal olItem As Object, Cancel As Boolean)
Dim Xl As Object ' Excel.Application
Dim Wb As Object ' Excel.Workbook
Set Xl = GetObject(, "excel.application")
Set Wb = Xl.Workbooks("NameOfYourOpenedWorkbook.xlsb")
Wb.Activate
Xl.activecell.Offset(0, 13).Value = Date & " " & Time
End Sub
So now when you send your automatically created email manually, you will get date and time captured in your opened Workbook in ActiveCell.Offset(0, 13) cell.
Add a VBA project reference to the Outlook object model, and add this class to your excel file:
''clsMail
Option Explicit
Public WithEvents itm As Outlook.MailItem
Public DestCell As Range '<< where to put the "sent" message
'you can add other fields here if you need (eg) to
' preserve some other info to act on when the mail is sent
Private Sub itm_Send(Cancel As Boolean)
Debug.Print "Sending mail with subject: '" & itm.Subject & "'"
DestCell.Value = "Mail sent!" '<< record the mail was sent
End Sub
Then in your Mail-sending code you can do something like this:
Option Explicit
Dim colMails As New Collection
Sub Tester()
Dim OutApp As Object
Dim OutMail As Object
Dim obj As clsMail
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(olMailItem)
With OutMail
.BodyFormat = olFormatHTML
.HTMLBody = "My eMail's HTML Body"
.To = "twilliams#theravance.com"
.CC = ""
.BCC = ""
.Subject = "Stock Request"
.Display
End With
'create an instance of the class and add it to the global collection colMails
Set obj = New clsMail
Set obj.itm = OutMail
Set obj.DestCell = ActiveCell.Offset(0, 13) '<< "sent" flag goes here
' when the user sends the mail
colMails.Add obj
End Sub
I have to create and send an Excel file every month via email to my boss.
I want to use a VBA code to send the file as attachment, but my VBA code doesn't work and asks for debug after confirmation.
My code:
Sub EMail()
ActiveWorkbook.SendMail Recipients:="user#gmail.com"
End Sub
Credit where credit is due... This is straight from the Ron de Bruin website.
Sub Mail_workbook_Outlook_1()
'Working in Excel 2000-2016
'This example send the last saved version of the Activeworkbook
'For Tips see: https://www.rondebruin.nl/win/s1/outlook/tips.htm
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = "ron#debruin.nl"
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.Body = "Hi there"
.Attachments.Add ActiveWorkbook.FullName
'You can add other files also like this
'.Attachments.Add ("C:\test.txt")
.Send 'or use .Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Here is an example on how to send Active Workbook as attachment
Option Explicit
Sub EmailFile()
Dim olApp As Object
Dim olMail As Object
Dim olSubject As String
' // Turn off screen updating
Application.ScreenUpdating = False
Set olApp = CreateObject("Outlook.Application")
Set olMail = olApp.CreateItem(olMailItem)
olSubject = "This Subject Line"
With olMail
.Display
End With
With olMail
.To = "0m3r#EMail.com"
.CC = ""
.BCC = ""
.Subject = olSubject
.HTMLBody = "This Body Text " & .HTMLBody
.Attachments.Add ActiveWorkbook.FullName
'.Attachments.Add ("C:\test.txt") ' add other file
' .Send 'or use .Display
.Display
End With
' // Restore screen updating
Application.ScreenUpdating = True
Set olMail = Nothing
Set olApp = Nothing
End Sub
You can use the VBA code snippet as shown in the following sample:
Sub SendEmailWithAttachment()
Dim myItem As Outlook.MailItem
Dim myAttachments As Outlook.Attachments
Set myItem = Application.CreateItem(olMailItem)
Set myAttachments = myItem.Attachments
myAttachments.Add "C:\MyExcelFile.xls", olByValue, 1, "Test"
myItem.To = "Recipient Address"
myItem.Send
'alternatively, you may display the item before sending
'myItem.Display
End Sub
Hope this may help.