Home > Blockchain >  VBA Send Email From Non-Default Account
VBA Send Email From Non-Default Account

Time:02-02

I am logged in with two Outlook Accounts, and I need to send an e-mail with the one that is not set to default.

I tried using .SendOnBehaulfOfName, but even though it showed me the right account prior to sending the email, after I sent it I saw that it was sent from the default email (which is the wrong one). I also tried using .SendUsingAccount but it did not change the "From" email.

    Dim OutlookApp As Object
    Dim OutlookMail As Object
    Dim ol As Outlook.Application
    Set ol = New Outlook.Application
    Set OutlookApp = CreateObject("Outlook.Application")
    Set OutlookMail = OutlookApp.CreateItem(0)

    With OutlookMail
        .To = lista_envio
        .CC = ""
        .BCC = ""
        .Subject = assunto_email
        .Display '
        .HTMLBody = mensagem
        .Attachments.Add (caminho)
        .SendUsingAccount = ol.Session.Accounts("Contato")
    End With

    Set OutlookMail = Nothing
    Set OutlookApp = Nothing
    Set ol = Nothing

Using the For each Account in Outlook.Application.Session.Accounts method also doesn't work.

Any ideas on what is wrong?

Thanks

CodePudding user response:

Make sure that such an account configured in Outlook. If you want to see changes on the Outlook UI you need to call the Display methods after setting all properties via the Outlook object model.

If the other account is configured in Outlook (not just an additional store) you need to choose the MailItem.SendUsingAccount property which sets an Account object that represents the account under which the MailItem is to be sent. You could find the following sample code which demonstartes how to use it:

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

The SendOnBehaulfOfName property doesn't require an account configured in Outlook. Only permissions are required for sending on behalf of another person in Exchange.

  • Related