0
votes

I am using Office 365 (Outlook Version 1909 Build 12026.20264).

I configured two email accounts ([email protected] and [email protected]) and one shared mailbox ([email protected]).

With my [email protected] account I have permission to send email from [email protected].

I can manually send email from all accounts ([email protected], [email protected], [email protected]).

I have VBA code to send email from [email protected] using the SentOnBehalfOfName property.

Sub TEST()
  Dim origEmail As MailItem
  Dim replyEmail As MailItem

  Set origEmail = Application.ActiveWindow.Selection.Item(1)
  Set replyEmail = Application.CreateItemFromTemplate("C:\...\Template.oft")

  replyEmail.SentOnBehalfOfName = "[email protected]"
  replyEmail.HTMLBody = replyEmail.HTMLBody & origEmail.Reply.HTMLBody
  replyEmail.Subject = "RE:" + origEmail.Subject

  replyEmail.Display
End Sub

Usually this sends emails correctly. I can see they go to the sent folder in the [email protected] account.

Sometimes it tries to send emails using the [email protected] account (which has no permission to send emails from [email protected]). I receive an error email in [email protected] and the email is not sent.

How can I change my code so that everytime I am sending email from [email protected] it will use my [email protected] account?

Note: I set my [email protected] account as my default account.

1

1 Answers

1
votes

You need to set the SendUsingAccount property to the Account object corresponding to the [email protected] mailbox.

Sub TEST()
  Dim origEmail As MailItem
  Dim replyEmail As MailItem

  Set origEmail = Application.ActiveWindow.Selection.Item(1)
  Set replyEmail = Application.CreateItemFromTemplate("C:\...\Template.oft")

  for each acc in Application.Session.Accounts
    if acc.DisplayName = "[email protected]" Then 
      replyEmail.SendUsingAccount = acc
      Exit for
    End If
  next 

  replyEmail.SentOnBehalfOfName = "[email protected]"
  replyEmail.HTMLBody = replyEmail.HTMLBody & origEmail.Reply.HTMLBody
  replyEmail.Subject = "RE:" + origEmail.Subject

  replyEmail.Display
End Sub