1

我正在使用以下代码通过简单 MAPI 接口发送电子邮件

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()

它似乎甚至适用于 Outlook 2007/2010,但它显示发送邮件的警告。

我可以使用扩展 MAPI 发送电子邮件而不显示警告和发送附件吗?如果是,我在哪里可以找到示例?

4

2 回答 2

1

不,您不能在 Python 中使用 Extended,您需要 C++ 或 Delphi。http://www.outlookcode.com/article.aspx?id=52提供了您的选项- 您可以安装最新的防病毒应用程序或使用扩展 MAPI 包装器,例如Redemption

于 2013-03-29T16:38:52.813 回答
0

对不起我的英语..
我找到了使用 PyWin32 在扩展 mapi 上添加附件的解决方案...
此代码是我的..我只添加了附件部分..
这会以 html 格式或文本格式向 Outlook 发送消息,包括嵌入在 html 中的附件(图像)和其他附件。
附件可以是每种类型的文件(.txt、.pdf、ecc ecc)
在此示例代码中,html 页面和附件文件必须位于此 py 的同一目录中代码。

Outlook 必须正常运行才能成功运行此代码。请参阅 MAPILogonEx .. https://msdn.microsoft.com/en-us/library/office/cc815545%28v=office.15%29.aspx
它使用 Outlook 发送邮件..因此,如果您在专用网络上,则 Autenticathion 部分刚刚完成了 Outlook 本身的运行.. :)

(感谢 Mark Hammond 的 PyWin32!)
(感谢 Dmitry Streblechenko 的 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>     

-->
于 2015-02-06T12:35:28.650 回答