pythonvbaoutlookmailbox

Getting the default Outlook signature in Python when generating email from a shared mailbox (similar to VBA)


The ask is to get the default signature from Outlook when generating an email from the code below. While the VBA code works effortlessly, the Python code is picking up the signature from the primary mailbox, even though it is specified to consider the shared mailbox. Additionally, the requirement is to save the sent email in the Sent Items folder of the shared mailbox, which is also not working as expected.

The goal is to use the shared mailbox as the base in Outlook to compose and send an email with any content, like "Hi all," to a specified address, and to automatically apply the default signature. I have two mailboxes in Outlook: my personal account and a shared mailbox. The automation works perfectly with the personal account but not with the shared mailbox. While VBA can do this successfully, Python cannot. Python fails to set the shared mailbox as the sender and defaults to the personal mailbox, applying its signature instead.

Sub DraftEmailFromSpecificMailbox111()
    Dim olApp As Outlook.Application
    Dim olNS As Outlook.Namespace
    Dim olAccount As Outlook.Account
    Dim olMail As Outlook.MailItem
    Dim olSignature As String
    Dim acc As Outlook.Account
    Dim targetEmail As String
    targetEmail = "sharedmailbox.india@xyz.com"    
    
    ' Initialize Outlook application and namespace
    Set olApp = New Outlook.Application
    Set olNS = olApp.GetNamespace("MAPI")
    
    ' Assign the specified mailbox to the olAccount variable
    For Each acc In olNS.Accounts
        If LCase(acc.SmtpAddress) = LCase(targetEmail) Then
            Set olAccount = acc
            Exit For
        End If
    Next acc

    If olAccount Is Nothing Then
        MsgBox "Account not found: " & targetEmail
        Exit Sub
    End If
    
    ' Create new mail item
    Set olMail = olApp.CreateItem(0) ' olMailItem
    
    ' Assign the account (no Set)
    olMail.SendUsingAccount = olAccount
    
    ' Display the email to load signature
    olMail.Display
    
    ' Capture the signature after display
    olSignature = olMail.HTMLBody
    
    ' Set subject, recipients, and body
    olMail.Subject = "Hi All"
    olMail.To = "abc.abc@abc.com;"
    olMail.HTMLBody = "Hi All,<br><br>" & olSignature
    
    ' Uncomment to send
    ' olMail.Send
    
    ' Cleanup
    Set olMail = Nothing
    Set olAccount = Nothing
    Set olNS = Nothing
    Set olApp = Nothing
End Sub

import win32com.client as win32

def send_email(to_email, subject, body):
    outlook = win32.Dispatch('Outlook.Application')
    namespace = outlook.GetNamespace("MAPI")
    accounts = namespace.Accounts

    shared_mailbox_email = "sharedmailbox.india@xyz.com"
    send_account = None

    # Find the account matching the shared mailbox email
    for account in accounts:
        if account.SmtpAddress.lower() == shared_mailbox_email.lower():
            send_account = account
            break

    if send_account is None:
        print(f"Shared mailbox account {shared_mailbox_email} not found.")
        return False

    try:
        # Create the email item
        mail = outlook.CreateItem(0)  # olMailItem

        # Assign the account BEFORE displaying
        mail.SendUsingAccount = send_account
        mail.SentOnBehalfOfName = send_account

        # Display the email to load the signature
        mail.Display()

        # Capture the signature (which is part of the HTMLBody after display)
        signature_html = mail.HTMLBody

        # Set the email subject and recipients
        mail.Subject = subject
        mail.To = to_email

        # Compose the message with your body plus the signature
        mail.HTMLBody = body + "<br><br>" + signature_html

        # Optionally, set the sent folder if needed
        # Find the shared mailbox folder
        shared_folder = None
        for folder in namespace.Folders:
            if folder.Name.lower() == shared_mailbox_email.lower():
                # Access the Sent Items folder inside the shared mailbox
                shared_folder = folder.Folders['Sent Items']
                break
        if shared_folder:
            mail.SentOnBehalfOfName = shared_mailbox_email
            mail.SaveSentMessageFolder = shared_folder

        # Send the email
        # mail.Send()
        return True

    except Exception as e:
        print(f"Error sending email: {e}")
        return False

# Example usage
send_email("abc.abc@abc.com", "Testing", "Hi All")

Solution

  • The line
    Set olMail = olApp.CreateItem(0)

    Creates message in the default store. If you want to create it in the shared mailbox, use Account.DeliveryStore.GetDefaultFolder(olFolderDrafts).Items.Add("IPM.Note")