Search code examples
vbaoutlookoutlook-addin

Setting the sender email address according to the recipient


How can I set programmatically in an email, to which I reply, the sender address to the recipient address?

enter image description here

Is there a way in VBA? I don't know where to start so I apologize because I cannot show any code.


Solution

  • Credit to @Al Bundy for correcting this. This solution is based on this post.

    In ThisOutlookSession:

    Option Explicit
    
    Private WithEvents objMail As MailItem
    Private assignmentHandled As Boolean
    
    'Set MailItem
    Private Sub Application_ItemLoad(ByVal Item As Object)
        If Item.Class = olMail And Not assignmentHandled Then
            Set objMail = Item
        End If
    End Sub
    
    'Handle reply/replayAll from triggering ItemLoad again
    Private Sub objMail_Open(Cancel As Boolean)
        assignmentHandled = True
    End Sub
    
    'Reply
    Private Sub objMail_Reply(ByVal Response As Object, Cancel As Boolean)
        Call SetSentOnBehalfOfName(Response)
    End Sub
    
    'Reply all
    Private Sub objMail_ReplyAll(ByVal Response As Object, Cancel As Boolean)
        Call SetSentOnBehalfOfName(Response)
    End Sub
    
    'MailItem closed
    Private Sub objMail_Close(Cancel As Boolean)
        assignmentHandled = False
    End Sub
    
    ' Avoid repeating code
    Private Sub SetSentOnBehalfOfName(ByRef Response As Object)
        Response.SentOnBehalfOfName = objMail.To
        assignmentHandled = False
    End Sub