Using different e-mail account to send mail - excel

I want to use a Excel macro to send a mail to a company. This mail should consist of a piece of text, a table and then the rest of the text.
In the function below I've compiled some code that works the way I want, but I would like to send the e-mail not from my personal account but from a corporate business account (in the code I refer to the latter as myemailadres#outlook.com). I think I have to use the .SendUsingAccount function, but if I implement it like shown below, the e-mail is send using my personal email account and not the one I specify. Can somebody help?
Sub Test()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim TargetSheet As String
Dim i As Long
Dim StrBodybegin As String
Dim StrBodyend As String
Dim Startcell
Dim TargetRow As Integer
TargetSheet = Range("L24").value 'L24 refers to a name of a company, there is also a sheet in the workbook with the exact same name.
With Application.WorksheetFunction 'this I copied from the code from Ron de Bruijn
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
TargetRow = .Match("TOTAAL", ThisWorkbook.Worksheets(TargetSheet).Range("W1:W60"), 0) 'setting range of table I want to copy
Set Startcell = ThisWorkbook.Worksheets(TargetSheet).Range("W15")
Set rng = ThisWorkbook.Worksheets(TargetSheet).Range(Startcell, ThisWorkbook.Worksheets(TargetSheet).Cells(TargetRow + 1, 38))
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
StrBodybegin = "Text 1"
StrBodyend = "Text 2"
On Error Resume Next
With OutMail
.To = ThisWorkbook.Worksheets("Voorblad").Range("L23").value 'L23 refers to email adress
.CC = ""
.BCC = ""
.Subject = "Subject"
.HTMLBody = StrBodybegin & RangetoHTML(rng) & StrBodyend 'using the Ron de Bruin function RangetoHTML to copy in the table defined by the rng
.SendUsingAccount = OutApp.Session.Accounts("myemailadres#outlook.com") 'the line that does not work :(
.Send
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End With
End Sub

You can use the property .SentOnBehalfOfName = "user#domain" if you have access to that mailbox or user or whatever. Even if it's not added to your outlook, like this:
Option Explicit
Sub Test()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim TargetSheet As String
Dim i As Long
Dim StrBodybegin As String
Dim StrBodyend As String
Dim Startcell
Dim TargetRow As Integer
TargetSheet = Range("L24").Value 'L24 refers to a name of a company, there is also a sheet in the workbook with the exact same name.
With Application.WorksheetFunction 'this I copied from the code from Ron de Bruijn
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
TargetRow = .Match("TOTAAL", ThisWorkbook.Worksheets(TargetSheet).Range("W1:W60"), 0) 'setting range of table I want to copy
Set Startcell = ThisWorkbook.Worksheets(TargetSheet).Range("W15")
Set rng = ThisWorkbook.Worksheets(TargetSheet).Range(Startcell, ThisWorkbook.Worksheets(TargetSheet).Cells(TargetRow + 1, 38))
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
StrBodybegin = "Text 1"
StrBodyend = "Text 2"
On Error Resume Next
With OutMail
.SentOnBehalfOfName = "user#domain"
.To = ThisWorkbook.Worksheets("Voorblad").Range("L23").Value 'L23 refers to email adress
.CC = ""
.BCC = ""
.Subject = "Subject"
.HTMLBody = StrBodybegin & RangetoHTML(rng) & StrBodyend 'using the Ron de Bruin function RangetoHTML to copy in the table defined by the rng
.SendUsingAccount = OutApp.Session.Accounts("myemailadres#outlook.com") 'the line that does not work :(
.Send
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End With
End Sub

Try, please:
.SendUsingAccount = outApp.GetNamespace("MAPI").accounts.Item("myemailadres#outlook.com")
And, when you try debugging, it is recommended to comment the line On Error Resume Next. You can not see where and what error appears. In fact, it should not exist at all, if everything is correct..

Find your account loop through accounts.
Dim outApp As object, outNS as object
Dim accounts As object, account As object, myAccount As object
set outApp =createobject("outlook.application")
set outNS = outApp.GetNamespace("MAPI")
Set accounts = outNS.Accounts
For Each account in accounts
if account.SmtpAddress = "myemailadrs#outlook.com" then
set myAccount = account
Exit For
end if
Next account
With outApp.CreateItem(0)
.to = "someone#abc.com"
'...
Set .SendUsingAccount = myAccount
'....
End With

Related

Send multiple emails with different deferred delivery times to one email address

I want to send email with deferred delivery according to the cells ("A2:A4").
For instance, if today is 2 February 2023, send three emails for delivery on 6 February, 13 February and 20 February.
The VBA code sends an email for last cell ("A4").
For ("A2") AND ("A3") the email won't be created.
Sub Send_Deferred_Mail_From_Excel()
Dim OutlookApp As Object
Dim OutlookMail As Object
Dim xRg As Range
Set xRg = Range("A2:A4")
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)
'Send Email Using Excel VBA Macro Code
With OutlookMail
.To = "email"
.CC = ""
.BCC = ""
.Subject = "HI"
.Body = "HELLO"
'Send email on specific day & time
.DeferredDeliveryTime = Range("A2") + Range("A3") + Range("A4")
.Display 'or just put .Send to directly send the mail instead of display
End With
Set OutlookMail = Nothing
Set OutlookApp = Nothing
End Sub
Please try it like this.
Make a list in Sheets("Sheet1") with :
In column A : Names of the people
In column B : E-mail addresses
In column C:Z : Filenames like this C:\Data\Book2.xls (don't have to be Excel files)
The Macro will loop through each row in "Sheet1" and if there is a E-mail address in column B
and file name(s) in column C:Z it will create a mail with this information and send it.
Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'Enter the path/file names in the C:Z column in each row
Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")
If cell.Value Like "?*#?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = cell.Value
.Subject = "Testfile"
.Body = "Hi " & cell.Offset(0, -1).Value
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Send 'Or use .Display
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
Sub Send_Deferred_Mail_From_Excel()
Dim OutlookApp As Object
Dim OutlookMail As Object
Dim xRg As Range
Set xRg = Range("A2:A4")
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)
'Send Email Using Excel VBA Macro Code
With OutlookMail
.To = "email"
.CC = ""
.BCC = ""
.Subject = "HI"
.Body = "HELLO"
''Try in a loop instead.
for each cell in xRg
'Send email on specific day & time
.DeferredDeliveryTime = cell
.Display 'or just put .Send to directly send the mail instead of display
next cell
End With
Set OutlookMail = Nothing
Set OutlookApp = Nothing
End Sub
I've got how to send multiple emails to one email address using date & time in cells
Sub Send_Deferred_Mail_From_Excel()
Dim i As Integer, OutlookMail As Object, lr As Long
Dim xRg As Range, Bk As Range
' get last row
lr = Cells(Rows.Count, "A").End(xlUp).Row
' create range from row 2 to last row
Set xRg = Range("A2:A" & lr)
Set OutlookMail = CreateObject("Outlook.Application")
For Each Bk In xRg
With OutlookMail.CreateItem(0)
.To = "email#gmail.com"
.CC = ""
.subject = "HI"
.Body = "HELLO"
' Send email on specific day & time
.DeferredDeliveryTime = Bk.Value
.Display
End With
Next Bk
End Sub

Sending multiple email using range with attachment in VBA

This is the first time I am trying from Excel to send email using VBA code.
Here is my structure of my Excel. Sometimes the email list will have 1 - 20 or only 1 also
A (col) B C D E F G
Sl.No First Name To Email CC Email Subj File to Send Message
Code:
Option Explicit
Sub SendMail()
Dim objOutlook As Object
Dim objMail As Object
Dim rngTo As Range
Dim rngSubject As Range
Dim rngBody As Range
Dim rngAttach As Range
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
With ActiveSheet
Set rngTo = .Range("C2")
Set rngSubject = .Range("E2")
Set rngBody = .Range("G2")
Set rngAttach = .Range("F2")
End With
With objMail
.To = rngTo.Value
.Subject = rngSubject.Value
.Body = rngBody.Value
.Attachments.Add rngAttach.Value
.Display
End With
Set objOutlook = Nothing
Set objMail = Nothing
Set rngTo = Nothing
Set rngSubject = Nothing
Set rngBody = Nothing
Set rngAttach = Nothing
End Sub
Here is my code this was working perfectly fine but for single emails to send, but not for multiple email.
I am struggling here to find how to send for multiple email with attachment using the tested code.
Maybe Try this:
Option Explicit
Sub SendMail()
Dim objOutlook As Object
Dim objMail As Object
Dim rngTo As Range
Dim rngSubject As Range
Dim rngBody As Range
Dim rngAttach As Range
Dim i As Integer
Set objOutlook = CreateObject("Outlook.Application")
For i = 2 To 21 ' Loop from 2 to 21
With ActiveSheet
Set rngTo = .Range("C" & i)
Set rngSubject = .Range("E" & i)
Set rngBody = .Range("G" & i)
Set rngAttach = .Range("F" & i)
End With
Set objMail = objOutlook.CreateItem(0)
With objMail
.To = rngTo.Value
.Subject = rngSubject.Value
.HTMLBody = "<B><U>" & rngBody.Value & ":</B></U>"
.Attachments.Add rngAttach.Value
.Display
End With
Set objMail = Nothing
Next
Set objOutlook = Nothing
Set rngTo = Nothing
Set rngSubject = Nothing
Set rngBody = Nothing
Set rngAttach = Nothing
End Sub
You can loop through the Range to generate 20 emails.
Update
Added .HTMLBody instead of .Body to make text Bold And Underlined
You can use more HTML commands to make certain portions of the Text Bold and More.
Try it this way.
Make a list in Sheets("Sheet1") with :
In column A : Names of the people
In column B : E-mail addresses
In column C:Z : Filenames like this C:\Data\Book2.xls (don't have to be Excel files)
The Macro will loop through each row in "Sheet1" and if there is a E-mail address in column B
and file name(s) in column C:Z it will create a mail with this information and send it.
Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'Enter the path/file names in the C:Z column in each row
Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")
If cell.Value Like "?*#?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = cell.Value
.Subject = "Testfile"
.Body = "Hi " & cell.Offset(0, -1).Value
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Send 'Or use .Display
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
https://www.rondebruin.nl/win/s1/outlook/amail6.htm
You need a loop for that. The below code will start with the second row and continue until it finds an empty row.
Option Explicit
Sub SendMail()
Dim objOutlook As Object
Dim objMail As Object
Dim rngTo As Range
Dim rngSubject As Range
Dim rngBody As Range
Dim rngAttach As Range
Set objOutlook = CreateObject("Outlook.Application")
Dim r As Long: For r = 2 To ActiveSheet.Range("C2").End(xlDown).Row
With ActiveSheet
Set rngTo = .Range("C" & r)
Set rngSubject = .Range("E" & r)
Set rngBody = .Range("G" & r)
Set rngAttach = .Range("F" & r)
End With
Set objMail = objOutlook.CreateItem(0)
With objMail
.to = rngTo.Value
.Subject = rngSubject.Value
.Body = rngBody.Value
.Attachments.Add rngAttach.Value
.Display
.Send ' If you want to send it without clicking
End With
Next
End Sub
Also note: These Set x = Nothing lines are superfluous, delete them because they just make the code less readable for humans. Regarding this issue you can also refer to this SO question: Is there a need to set Objects to Nothing inside VBA Functions
Update
Sorry this line has to be inside the loop, I updated the code:
Set objMail = objOutlook.CreateItem(0)

How to paste email addresses from clipboard into Outlook "To" field?

Trying to setup VBA code that will take a selection of Excel cells which contain email addresses (with a semi-colon at the end of each address to allow for multiple emails when pasted) and insert those into the "To" field in an new Outlook email. When I execute the below code, it only inserts the email addresses into the Body of the Outlook email, not the "To" field. Is there a way to fix this or will I need to approach this in a completely different fashion?
Here is my code:
Sub Test2()
Dim OutApp As Object
Dim OutMail As Object
Dim Subj As String
Dim oiInsp As Object
Dim wdDoc As Object
Dim oRng As Object
'Copy the email addresses to the clipboard
Range("B2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
'Create Outlook object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
'Trying to add the email address to the "To" field in the email
With OutMail
.Display
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
Set oRng = wdDoc.Range
.To = oRng.Paste
'This will resolve all the addresses in the email to ensure they exist in your contacts, otherwise pops up error
If Not .Recipients.ResolveAll Then
For Each Recipient In .Recipients
If Not Recipient.Resolved Then
MsgBox Recipient.Name & " could not be resolved"
End If
Next
End If
End With
On Error GoTo 0
Set OutApp = Nothing
Set OutMail = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
Set oRng = Nothing
End Sub
Try creating a string of recipients instead - you can't paste a range to the .To like that.
Sub Test2()
Dim OutApp As Object
Dim OutMail As Object
Dim Subj As String
Dim oiInsp As Object
Dim wdDoc As Object
Dim oRng As Object
Dim lastrow As Long, i As Long
Dim recipstring As String
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
For i = 2 To lastrow
If i = 2 Then
recipstring = Range("B" & i).Value
Else
recipstring = recipstring & ";" & Range("B" & i).Value
End If
Next i
'Create Outlook object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
'Trying to add the email address to the "To" field in the email
With OutMail
.Display
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
Set oRng = wdDoc.Range
.to = recipstring
'This will resolve all the addresses in the email to ensure they exist in your contacts, otherwise pops up error
If Not .Recipients.ResolveAll Then
For Each Recipient In .Recipients
If Not Recipient.Resolved Then
MsgBox Recipient.Name & " could not be resolved"
End If
Next
End If
End With
On Error GoTo 0
Set OutApp = Nothing
Set OutMail = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
Set oRng = Nothing
End Sub

Trouble in sending the mail to multiple recipients at the same time from outlook vba

here I am trying to send out a mail to multiple recipients from outlook vba.
the recipient mail address is taken from column A of excel sheet. Whne I run the below code the error "Run Time error 1004; Method 'cells of object'_Global' failed"
how to send the same mail to multiple recipients at the same time.
To:Abc#gmail.Com; bhy#gmail.com; rft#gmail.com CC:hjuy#gmail.com;
ijk#gmail.com Subject: test mail
Code:
Sub Sendmail()
Dim olItem As Outlook.MailItem
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSht As Excel.Worksheet
Dim sPath As String
Dim iRow As Long
iRow = 1
sPath = "XX"
' // Excel
Set xlApp = CreateObject("Excel.Application")
' // Workbook
Set xlBook = xlApp.Workbooks.Open(sPath)
' // Sheet
Set xlSht = xlBook.Sheets("Sheet1")
Do Until IsEmpty(Cells(iRow, 1))
Recip = Cells(iRow, 1).Value
' subject = Cells(iRow, 2).Value
' Atmt = Cells(iRow, 3).Value '
' // Create e-mail Item
Set olItem = Application.CreateItem(olMailItem)
With olItem
Set olRecip = .Recipients.Add(Recip)
.CC = xlSht.Range("B1")
.subject = "test"
.Display
.Send
End With
' // Close
xlBook.Close SaveChanges:=True
' // Quit
xlApp.Quit
'// CleanUp
iRow = iRow + 1
Loop
Set xlApp = Nothing
Set xlBook = Nothing
Set xlSht = Nothing
Set olItem = Nothing
End Sub
This should od the job for you.
Make a list in Sheets("Sheet1") with :
In column A : Names of the people
In column B : E-mail addresses
In column C:Z : Filenames like this C:\Data\Book2.xls (don't have to be Excel files)
The Macro will loop through each row in "Sheet1" and if there is a E-mail address in column B
and file name(s) in column C:Z it will create a mail with this information and send it.
Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'Enter the path/file names in the C:Z column in each row
Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")
If cell.Value Like "?*#?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = cell.Value
.Subject = "Testfile"
.Body = "Hi " & cell.Offset(0, -1).Value
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Send 'Or use .Display
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
https://www.rondebruin.nl/win/s1/outlook/amail6.htm

Email a single attachment from folder of files each to a different person

I have a folder with 50 files and I have a list of 50 email addresses. Each file goes to a different email address. Is there a way to write a macro that performs this task?
The problem with the set of code below is two-fold:
1) I have 3 COLUMNS of data in an Excel file: One for subject, one for email address to send to, and the third for the FILE PATH of where the attachment to be attached is stored.
The code below does not allow for a pre-determined set of subject arguments. It also uses ROWS?? for the filepath field instead of a column like it does for send to? So confusing.
Sub Send_Files()
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'Enter the path/file names in the C:Z column in each row
Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")
If cell.Value Like "?*#?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = cell.Value
.Subject = "Testfile"
.Body = "Hi " & cell.Offset(0, -1).Value
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Send 'Or use .Display
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
Here is quick example, assuming col A = Email, Col B = Subject & Col C = Path
Option Explicit
Public Sub Example()
Dim olApp As Object
Dim olMail As Object
Dim olRecip As Object
Dim olAtmt As Object
Dim iRow As Long
Dim Recip As String
Dim Subject As String
Dim Atmt As String
iRow = 2
Set olApp = CreateObject("Outlook.Application")
Dim Sht As Worksheet
Set Sht = ThisWorkbook.Worksheets("Sheet1")
Do Until IsEmpty(Sht.Cells(iRow, 1))
Recip = Sht.Cells(iRow, 1).Value
Subject = Sht.Cells(iRow, 2).Value
Atmt = Sht.Cells(iRow, 3).Value ' Attachment Path
Set olMail = olApp.CreateItem(0)
With olMail
Set olRecip = .Recipients.Add(Recip)
.Subject = Subject
.Body = "Hi "
.Display
Set olAtmt = .Attachments.Add(Atmt)
olRecip.Resolve
End With
iRow = iRow + 1
Loop
Set olApp = Nothing
End Sub

Resources