Question

i am using the following code to send email with Simple MAPI Interface

import win32com.client
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "I AM SUBJECT!!"
newMail.Body = "I AM IN THE BODY\nSO AM I!!!"
newMail.To = "themail@mail.org"
#newMail.CC = "moreaddresses here"
#newMail.BCC = "aaa"
#attachment1 = "Path to attachment no. 1"
#attachment2 = "Path to attachment no. 2"
#newMail.Attachments.Add(attachment1)
#newMail.Attachments.Add(attachment2)
#newMail.display()
newMail.Send()

It seems to work even with Outlook 2007/2010, but it shows a warning for sending the mail.

Can I use Extended MAPI for sending emails without showing the warning, and sending attachments? If yes, where can I find an example?

Was it helpful?

Solution

No, you cannot use Extended with Python, you will need C++ or Delphi. Your options are given at http://www.outlookcode.com/article.aspx?id=52 - you can either install an up to date antivirus app or use an Extended MAPI wrapper, such as Redemption.

OTHER TIPS

Sorry for my english language..
I found a solution to add attachment on extended mapi using PyWin32 ...
This code isn'mine .. I added only the attachments part..
This sends message to outlook in html format or text format, including attachment embedded in html (the images) and other attachments..
The attachments can be every type file (.txt, .pdf, ecc ecc)
In this example code the html page and the attachments files must be in the same directory of this py code.

Outlook must be working to run this code successfully.. See MAPILogonEx .. https://msdn.microsoft.com/en-us/library/office/cc815545%28v=office.15%29.aspx
It use outlook for sending mails.. So if you are on a private net the Autenticathion part is just done running Outlook itself.. :)

(thanks to Mark Hammond for PyWin32!)
(thanks to Dmitry Streblechenko for OutlookSpy!)


from win32com.mapi import mapi
from win32com.mapi import mapitags
from win32com.mapi.mapitags import PROP_TAG, PT_UNICODE, PT_BINARY

import os


def Add_Message_AttachList(Message, AttachList, PathAttach, ContentIDList = None):

    """
    Add  a AttachList to a message

    :param Message: string       message for the Attach list
    :param AttachList: string    comma separated list of attachments
    :param PathAttach:  string   path of the attachments
    :param ContentIDList: string None if attachments aren't embedded
                                 comma separated list of ContentsID if embedded

    """

    # defines some costants
    METHOD = 0
    RENDERING = 1
    PATH = 2
    LONG_PATH = 3
    FILENAME = 4
    DISPLAY_NAME = 5
    DATA_BIN = 6
    NUM_ATT_PROPS = 7

    if ContentIDList:
        CONTENT_ID = 7
        NUM_ATT_PROPS = 8
        ID_List = ContentIDList.split(",")

    from collections import namedtuple

    sPropValue = namedtuple("sPropValue", "ulPropTag Value")
    file_name_index = 0
    for file_name in AttachList.split(","):

        my_file = open(PathAttach + "//" + file_name, "rb")
        file_buffer = my_file.read()
        my_file.close()

        spvAttach = [''] * NUM_ATT_PROPS
        spvAttach[METHOD] = sPropValue(mapitags.PR_ATTACH_METHOD, mapi.ATTACH_BY_VALUE)
        spvAttach[RENDERING] = sPropValue(mapitags.PR_RENDERING_POSITION, -1)
        spvAttach[PATH] = sPropValue(mapitags.PR_ATTACH_PATHNAME, PathAttach + "//" + file_name)
        spvAttach[LONG_PATH] = sPropValue(mapitags.PR_ATTACH_LONG_PATHNAME, PathAttach + "//" + file_name)
        spvAttach[FILENAME] = sPropValue(mapitags.PR_ATTACH_FILENAME, file_name)
        spvAttach[DISPLAY_NAME] = sPropValue(mapitags.PR_DISPLAY_NAME_A, file_name)
        spvAttach[DATA_BIN] = sPropValue(mapitags.PR_ATTACH_DATA_BIN, file_buffer)


        # defines the property PR_ATTACH_CONTENT_ID_W  not defined  in pywin32 mapitags.
        # number of PR_ATTACH_CONTENT_ID_W Property is in MSDN Library
        # https://msdn.microsoft.com/en-us/library/cc765868.aspx
        # all mapi tags are defined in https://msdn.microsoft.com/en-us/library/cc815492%28v=office.15%29.aspx
        mapitags.PR_ATTACH_CONTENT_ID_W = PROP_TAG(PT_UNICODE, 0x3712)

        if ContentIDList:
            spvAttach[CONTENT_ID] = sPropValue(mapitags.PR_ATTACH_CONTENT_ID_W, ID_List[file_name_index])

        file_name_index += 1
        # create a attachment
        pAtt = Message.CreateAttach(None, 0)
        # set the properties of the attachment
        pAtt[1].SetProps(spvAttach)
        # save the properties of the attachment
        pAtt[1].SaveChanges(0)

# ----------------------End Add_Message_AttachList ----



def SendEMAPIMail(is_HTML, subject = "", messageText = "", sendAttachs = None, sendAttachEmbeddeds = None,
                  sendAttachEmbeddedIDs = None,
                  sendTo = None, sendCC = None, sendBCC = None, mAPIProfile = None):
    """
    Sends an email to the recipient using the extended MAPI interface

    subject and messageText are strings
    sendAttachs is a comma-separated attachments list
    Send{To,CC,BCC} are comma-separated address lists
    MAPIProfile is the name of the MAPI profile
    """

    myPathFile = os.getcwdu()
    # initialize and log on
    mapi.MAPIInitialize(None)
    session = mapi.MAPILogonEx(0, mAPIProfile, None, mapi.MAPI_EXTENDED | mapi.MAPI_USE_DEFAULT)
    messagestorestable = session.GetMsgStoresTable(0)
    messagestorestable.SetColumns((mapitags.PR_ENTRYID, mapitags.PR_DISPLAY_NAME_A, mapitags.PR_DEFAULT_STORE), 0)

    while True:
        rows = messagestorestable.QueryRows(1, 0)
        if len(rows) != 1:
            break
        row = rows[0]
        if (mapitags.PR_DEFAULT_STORE, True) in row:
            break


    # unpack the row and open the message store
    (eid_tag, eid), (name_tag, name), (def_store_tag, def_store) = row
    msgstore = session.OpenMsgStore(0, eid, None, mapi.MDB_NO_DIALOG | mapi.MAPI_BEST_ACCESS)

    # get the outbox
    hr, props = msgstore.GetProps(mapitags.PR_IPM_OUTBOX_ENTRYID, 0)
    (tag, eid) = props[0]
    outboxfolder = msgstore.OpenEntry(eid, None, mapi.MAPI_BEST_ACCESS)

    # create the message and the addrlist
    message = outboxfolder.CreateMessage(None, 0)
    # note: you can use the resolveaddress functions for this. but you may get headaches
    pal = []

    def makeentry(recipient, recipienttype):
        return ((mapitags.PR_RECIPIENT_TYPE, recipienttype),
                (mapitags.PR_SEND_RICH_INFO, False),
                (mapitags.PR_DISPLAY_TYPE, 0),
                (mapitags.PR_OBJECT_TYPE, 6),
                (mapitags.PR_EMAIL_ADDRESS_A, recipient),
                (mapitags.PR_ADDRTYPE_A, 'SMTP'),
                (mapitags.PR_DISPLAY_NAME_A, recipient))

    if sendTo:
        pal.extend([makeentry(recipient, mapi.MAPI_TO) for recipient in sendTo.split(",")])
    if sendCC:
        pal.extend([makeentry(recipient, mapi.MAPI_CC) for recipient in sendCC.split(",")])
    if sendBCC:
        pal.extend([makeentry(recipient, mapi.MAPI_BCC) for recipient in sendBCC.split(",")])

    # add the resolved recipients to the message
    message.ModifyRecipients(mapi.MODRECIP_ADD, pal)

    # add attachments
    if sendAttachs:
        Add_Message_AttachList(message, sendAttachs, myPathFile, None)
    # add attachments embedded in the html message
    if sendAttachEmbeddeds:
        Add_Message_AttachList(message, sendAttachEmbeddeds, myPathFile, sendAttachEmbeddedIDs)


    if is_HTML:
        # defines the property PR_HTML  not defined  in pywin32 mapitags.
        # number of PR_HTML Property is in MSDN Library
        # https://msdn.microsoft.com/en-us/library/cc842395.aspx
        # all mapi tags are defined in https://msdn.microsoft.com/en-us/library/cc815492%28v=office.15%29.aspx
        mapitags.PR_HTML = PROP_TAG(PT_BINARY, 0x1013)
        message.SetProps([(mapitags.PR_HTML, messageText),
                          (mapitags.PR_SUBJECT_W, subject)])
    else:
        message.SetProps([(mapitags.PR_BODY_W, messageText),
                          (mapitags.PR_SUBJECT_W, subject)])


    # save changes and submit
    outboxfolder.SaveChanges(0)
    message.SubmitMessage(0)
    # close the extended mapi session
    # session.Logoff(0, 0, 0)

# ------------------END  SendEMAPIMail------



if __name__ == '__main__':
    # initialize....
    MAPIProfile = ""
    ImageEmbeddeds = None
    ImageEmbeddedIDs = None
    is_HTML = True    # if True il messaggio has html format
                      # else the message has text format.

    # list_to

    SendTo = "abc@xy.it,cdef@mail.it"

        # subject message
    SendSubject = "Paperino HTML"

        # simple text message
    s = "text message"

    if is_HTML:
        # my_page.html  is the message with HTML format
        mio_file = open("my_page.html", "rb")
        s = mio_file.read()
        mio_file.close()
        ImageEmbeddeds = "paperino.jpg"  # image HTML list, None for none immagine
        ImageEmbeddedIDs = "paperino"    # imageID HTML list, None for none ID

    SendMessage = s
        # attach list  , None for  no file.
    SendAttachs = "file1.txt"




    SendEMAPIMail(is_HTML, SendSubject, SendMessage,
                  SendAttachs, ImageEmbeddeds, ImageEmbeddedIDs,
                  SendTo, None, None, MAPIProfile)
    print "Done!"

-----------------------------------------------------------------------------
my_page.html
HTML File..  image attribute cid is the same into ImageEmbeddedIDs
this html code is commented for viewing
<!--
<!doctype html>
<html lang="it">
    <head>
        <meta 
            http-equiv="Content-Type" 
            content="text/html; charset = utf-8" 
        />  
        <title>Paperino</title>
    </head>
    <body>
        <p align="center">
          <img src="cid:paperino" width="77" height="77">
          <p align="center">Hi to all!</p>
          <hr align="left" size="1">
          <p align="left">Amd</p>
        </p>
    </body>
</html>     

-->
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top