I am using the following code to send emails through Outlook using VBA. I am using my work computer with my work email as the main account, but want to send from another account that is logged in. As I am new to VBA, I have not managed to integrate any of the code I have found online. The rest of the code works as desired, it's just the sender account being the issue.
Can anyone help amending the code? (The below code is without my attempt of fixing it)
Sub Test1()
Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range
Dim strbody As String
For Each cell In Range("D2:D2")
strbody = strbody & cell.Value & vbNewLine
Next
Application.ScreenUpdating = False
Set OutApp = CreateObject("Outlook.Application")
On Error GoTo cleanup
For Each cell In Columns("A").Cells.SpecialCells(xlCellTypeConstants)
If cell.Value Like "?*@?*.?*" And _
LCase(Cells(cell.Row, "C").Value) = "yes" Then
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = cell.Value
.Subject = "A personal message from the founder"
.Body = "Hi " & Cells(cell.Row, "B").Value & vbNewLine & vbNewLine & strbody
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
End If
Next cell
cleanup:
Set OutApp = Nothing
Application.ScreenUpdating = True
End Sub
CodePudding user response:
Do you mean send from another email address? If so just add :
.SentOnBehalfOfName = "[email protected]" 'Change to the email address you want to send from
e.g
With OutMail
.To = cell.Value
.SentOnBehalfOfName = "[email protected]"
.Subject = "A personal message from the founder"
.Body = "Hi " & Cells(cell.Row, "B").Value & vbNewLine & vbNewLine & strbody
.Send
End With
CodePudding user response:
There are two possible ways in Outlook:
- If another account is configured in Outlook you need to use the MailItem.SendUsingAccount property which returns or sets an
Accountobject that represents the account under which theMailItemis to be sent.
Sub SendUsingAccount()
Dim oAccount As Outlook.account
For Each oAccount In Application.Session.Accounts
If oAccount.AccountType = olPop3 Then
Dim oMail As Outlook.MailItem
Set oMail = Application.CreateItem(olMailItem)
oMail.Subject = "Sent using POP3 Account"
oMail.Recipients.Add ("[email protected]")
oMail.Recipients.ResolveAll
Set oMail.SendUsingAccount = oAccount
oMail.Send
End If
Next
End Sub
- If you have got permissions set by the Exchange admin to send on behalf of another person you need to use the MailItem.SentOnBehalfOfName property which returns a string indicating the display name for the intended sender of the mail message.
