Search code examples
pythonemailoutlook-2010pywin32account

Python - Sending Outlook email from different address using pywin32


I have a working script that creates and sends Outlook emails successfully through pywin32, but I would like to send the email from a different, generic account. I have access to this generic account (and password) and even have the mailbox opened concurrently in Outlook, if that helps.

Trying something like msg.From = "[email protected]" returns AttributeError: Property 'CreateItem.From' can not be set..

Is there any way to accomplish this without using SMTP? Even just changing the headers to reflect the generic account as the From and Reply-To address would work.

Edit: Using Win7 32bit, Outlook 2010, python 2.7, and the pywin32 module to create the following bit of code:

from win32com.client import Dispatch
mailer = Dispatch("Outlook.Application")
msg = mailer.CreateItem(0)
msg.To = emailTo
msg.CC = emailCC
msg.Subject = emailSubject
msg.Body = emailBody
msg.Send()

This part works perfectly fine, but it sends the emails through the user that's logged in, myself. I'd rather send it from a generic account so that it looks more official and replies are received there instead of in my mailbox.


Solution

  • You can send mails via exchange using the extended mapi. It takes a little more effort than what you tried so far but it is very powerful, e.g. it allows to select an outlook profile to be used. Have a look at site-packages\win32comext\mapi\demos\mapisend.py of your pywin32 installation.

    EDIT:

    As said in the comment, try the following to be sure Outlook is using the profile you want. Look for this line:

    session = mapi.MAPILogonEx(0, MAPIProfile, None, mapi.MAPI_EXTENDED |
                               mapi.MAPI_USE_DEFAULT)
    

    and change it to

    session = mapi.MAPILogonEx(0, MAPIProfile, None, mapi.MAPI_EXTENDED |
                               mapi.MAPI_LOGON_UI)
    

    Call SendEMAPIMail like this:

    SendEMAPIMail(SendSubject, SendMessage, SendTo, MAPIProfile=None)
    

    A dialog should appear offering to select the Outlook profile.

    EDIT:

    As @caseodilla found out, if Outlook is running with another profile, MAPILogonEx seems to reuse the running session and its profile. In order to force mapi to use another profile add the MAPI_NEW_SESSION flag:

    session = mapi.MAPILogonEx(0, MAPIProfile, None, mapi.MAPI_EXTENDED |
                               mapi.MAPI_LOGON_UI | mapi.MAPI_NEW_SESSION)