使用 Python 在 Mac 上自动化 Outlook

Jay*_*don 8 python macos outlook python-3.x

我可以使用 win32/COM 在 Windows 上自动化 Outlook,但是有人知道在 mac osx 上执行相同操作的纯 python 方法吗?

一个简单的用例是:

  • 打开 Outlook/连接到活动实例
  • 启动空白的新电子邮件

我想创建一个应用程序来创建电子邮件模板并附加文件,然后让用户完成电子邮件编辑并在准备好时发送,而不仅仅是发送电子邮件。

是否有一个可以工作的 applescript 的 python 包装器?(我对 applescript 一无所知,所以一个例子会有所帮助)。

Jay*_*don 9

@ajrwhite 添加附件有一个技巧,您需要使用 mactypes 中的“别名”将字符串/路径对象转换为 mactypes 路径。我不知道为什么,但它有效。

这是一个与收件人创建消息并可以添加附件的工作示例:

from appscript import app, k
from mactypes import Alias
from pathlib import Path

def create_message_with_attachment():
    subject = 'This is an important email!'
    body = 'Just kidding its not.'
    to_recip = ['myboss@mycompany.com', 'theguyih8@mycompany.com']

    msg = Message(subject=subject, body=body, to_recip=to_recip)

    # attach file
    p = Path('path/to/myfile.pdf')
    msg.add_attachment(p)

    msg.show()

class Outlook(object):
    def __init__(self):
    self.client = app('Microsoft Outlook')

class Message(object):
    def __init__(self, parent=None, subject='', body='', to_recip=[], cc_recip=[], show_=True):

        if parent is None: parent = Outlook()
        client = parent.client

        self.msg = client.make(
            new=k.outgoing_message,
            with_properties={k.subject: subject, k.content: body})

        self.add_recipients(emails=to_recip, type_='to')
        self.add_recipients(emails=cc_recip, type_='cc')

        if show_: self.show()

    def show(self):
        self.msg.open()
        self.msg.activate()

    def add_attachment(self, p):
        # p is a Path() obj, could also pass string

        p = Alias(str(p)) # convert string/path obj to POSIX/mactypes path

        attach = self.msg.make(new=k.attachment, with_properties={k.file: p})

    def add_recipients(self, emails, type_='to'):
        if not isinstance(emails, list): emails = [emails]
        for email in emails:
            self.add_recipient(email=email, type_=type_)

    def add_recipient(self, email, type_='to'):
        msg = self.msg

        if type_ == 'to':
            recipient = k.to_recipient
        elif type_ == 'cc':
            recipient = k.cc_recipient

        msg.make(new=recipient, with_properties={k.email_address: {k.address: email}})
Run Code Online (Sandbox Code Playgroud)


Jay*_*don 7

使用py-appscript解决了这个问题

pip install appscript
Run Code Online (Sandbox Code Playgroud)
from appscript import app, k

outlook = app('Microsoft Outlook')

msg = outlook.make(
    new=k.outgoing_message,
    with_properties={
        k.subject: 'Test Email',
        k.plain_text_content: 'Test email body'})

msg.make(
    new=k.recipient,
    with_properties={
        k.email_address: {
            k.name: 'Fake Person',
            k.address: 'fakeperson@gmail.com'}})

msg.open()
msg.activate()
Run Code Online (Sandbox Code Playgroud)

下载 py-appscript 的 ASDictionary 和 ASTranslate 工具将 AppleScript 示例转换为 python 版本也非常有用。