Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add signature to outlook email with python using win32com

Does anyone know how to add an email signature to an email using win32com?

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'TO'
mail.Subject = 'SUBJECT'
mail.HTMLbody = 'BODY'
mail.send
like image 994
Michael David Avatar asked Aug 25 '15 16:08

Michael David


People also ask

How do I automate my email signature?

Insert a signature automaticallyOn the Message tab, in the Include group, click Signature, and then click Signatures. Under Choose default signature, in the E-mail account list, click an email account with which you want to associate the signature.


2 Answers

A fully functional e-mailer function with signature included, using code from the answer above:

def Emailer(message, subject, recipient):
    import win32com.client as win32   

    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = recipient
    mail.Subject = subject
    mail.GetInspector 

    index = mail.HTMLbody.find('>', mail.HTMLbody.find('<body')) 
    mail.HTMLbody = mail.HTMLbody[:index + 1] + message + mail.HTMLbody[index + 1:] 

    mail.Display(True)
    #mail.send #uncomment if you want to send instead of displaying

then call

Emailer("Hi there, how are you?", "Subject", "[email protected]")
like image 152
David Avatar answered Sep 29 '22 09:09

David


Outlook signatures are not exposed through the Outlook Object Model. The best you can do is read the signature from the file system and add its contents to the HTML body appropriately. Keep in mind that two HTML strings must be merged, not just concatenated. You would also need to merge the styles from two HTML documents and take care of the embedded images used by the signature.

Note that Outlook adds a signature when an unmodified message is displayed or its inspector is touched

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'TO'
mail.Subject = 'SUBJECT'
mail.GetInspector 

mail.HTMLBody now contains the message signature that you will need to merger (not just concatenate!) with your own HTML

UPDATE: as of the latest (Summer 2016) builds of Outlook, GetInspector trick no longer works. Now Only MailItem.Display adds the signature to an unmodified message.
If you want to programmatically insert a signature, Redemption (I am its author) exposes RDOSignature object which implements ApplyTo method (it handles the signature image files and merges HTML styles appropriately).

like image 29
Dmitry Streblechenko Avatar answered Sep 29 '22 07:09

Dmitry Streblechenko