Sending an Email from Excel when Outlook not available using VBA - excel

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/

Related

Excel macro to send an email generates runtime error 287

I referenced many websites and even copied and pasted code. I cannot get my Excel macro button to send an email.
When I click RunSub/Userform(play button) in VBAProject I get
runtime error 287
Sub Send_Email()
Dim MyOutlook As Object
Set MyOutlook = CreateObject("Outlook.Application")
Dim MyMail As Object
Set MyMail = MyOutlook.CreateItem(olMailItem)
MyMail.To = "notlistedpublicly"
MyMail.Subject = Range("B6") & "Has completed his Skills Matrix"
MyMail.Body = Range("B6") & "has completed his Skills Matrix. Please review"
MyMail.Send
End Sub
I have a similar code, I added some lines to from it to your code.
Sub Send_Email()
Dim MyOutlook As Object
Set MyOutlook = CreateObject("Outlook.Application")
Dim MyMail As Object
'I change this
'Set MyMail = MyOutlook.CreateItem(olMailItem)
Set MyMail = MyOutlook.CreateItem(0)
MyOutlook.Session.Logon
With MyMail
.To = "notlistedpublicly"
.Subject = Range("B6") & "Has completed his Skills Matrix"
.Body = Range("B6") & "has completed his Skills Matrix. Please review"
'Before try to see how the mail looks.
'.Send
.Display
End with
Set MyMail = Nothing
Set MyOutlook = Nothing
End Sub

How to send email from a specific Outlook account using Excel?

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.

AddAttachment in excel VBA not able to attach file in outlook

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

Open mail template in excel via vba and fill template with excel data

I need some help using excel for filling a mail template.
My problem right now is how to open the template with a macro
I wrote this:
Sub OpenMail()
Open "L:\Projekte\Abteilung\Projekt\Vorlage_deutsch" For Input As #1
End Sub
Running this macro it throws me an error that says data can not be found.
Is there a way to save the template in excel directly instead of trying to open it from the computer?
Also if you have any idea on how to fill the email with the data of my rows in excel that would be really helpful!
Thanks!!
Here is sample code to open an outlook mail template.
Sub CreateMailInExcel()
Dim olApp As Object
Set olApp = Outlook.Application
Dim Msg As Outlook.MailItem
''Debug.Print (olApp.ProductCode)
Set Msg = olApp.CreateItemFromTemplate("D:\Test\untitled.oft")
Msg.Display
'Set Msg = Nothing
Set olApp = Nothing
End Sub
The extension of outlook mail template is .oft
You need to set reference to Microsoft Outlook 15.0 Object Library.
Below sub is simple type a mail with data from excel cells. You have to adjust codes for your need.
Option Explicit
Sub SendMail()
Dim sendTo As String
Dim strBody As String
Dim strSubject As String
Dim OutApp As Object
Dim OutMail As Object
Dim strMail as String
'Ad referrence ---> Microsoft Outlook 12.0 object library
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(olMailItem)
strMail = Range("A1") ' Email address in A1 cell
strBody = Range("B1") ' Subject text in B1 cell
strSubject = Range("C1") ' Message body in C1 cell
With OutMail
'.Attachments.Add ThisWorkbook.Path & "\TestFile.pdf"
.To = strMail
.Subject = strSubject
.HTMLBody = strBody
.Display 'Show mail message.
'.Send 'Direct send
End With
' Application.Wait (Now + TimeValue("0:00:02"))
' Application.SendKeys "%s"
End Sub

Capturing Outlook Email Send Time In Excel VBA

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

Resources