python - 使用 Exchangelib 更改发件人帐户

标签 python python-3.x outlook exchangelib

我在 Outlook 上有两个帐户“user1@example.com”和“user2@example.com”。我的 user1 草稿文件夹中有许多草稿,并且希望在发送之前将每封电子邮件更新到 user2 地址,以便 user2 成为电子邮件的发件人并显示在邮件项目的发件人字段中。

使用 exchangelib我设法将“发件人”和“帐户”地址从 user1 更改为 user2(甚至使用 print(item.sender, item.account) 来验证更改),但更新并未反射(reflect)完成后,从 Outlook 草稿文件夹中的字段发送电子邮件。

import getpass
from exchangelib import Configuration
from exchangelib import Credentials, Account
from exchangelib import FileAttachment, HTMLBody
from exchangelib.properties import DistinguishedFolderId


def authenticate():
    """
    Authenticate into mail.example.com
    """
    email = "user1@example.com"
    passwd = getpass.getpass(prompt="Enter your password: ")
    user_credentials = Credentials(email, passwd)
    config = Configuration(server="mail.example.com",
                           credentials=user_credentials)
    account = Account(primary_smtp_address=email, config=config,
                           credentials=user_credentials, autodiscover=False)
    return account

def main():
    """
     Change sender account to user2@example.com
    """
    user_account = authenticate()
    drafts = DistinguishedFolderId('drafts')
    for item in user_account.drafts.all().order_by('subject'):
        item.sender = 'user2@example.com'
        item.account = 'user2@example.com'
        user_account.drafts.save(update_fields=['sender', 'account'])
        exit("Done")

if __name__ == "__main__":
    main()

最佳答案

您需要对项目而不是文件夹调用.save()Folder.save() 用于更改文件夹本身的属性,例如文件夹名称。

按照其他答案中的建议打印项目只会告诉您该项目的本地副本已更改,而不是服务器上的实际项目。您需要调用 item.refresh() 来查看实际更新的内容(尽管在您调用 item.save() 时应该始终匹配)。

最后,item.account 是对 Account 对象的引用。不要改变这一点。包含发件人信息的两个字段是 item.senderitem.author,但 item.sender 是由服务器自动设置的,无法更改改变了。 item.author 可以更改,但仅限于消息仍为草稿时。以下是 Exchangelib 中消息特定字段定义的链接:https://github.com/ecederstrand/exchangelib/blob/3158c076a1e30a18e0b68e99a54fb14b3a6f7cd4/exchangelib/items/message.py#L18 .

这是一个例子:

    for item in user_account.drafts.all().order_by('subject'):
        item.author = 'user2@example.com'
        item.save()
        item.refresh()  # This gets a fresh copy of the item on the server
        print(item)  # Now you see whatever the server has

关于python - 使用 Exchangelib 更改发件人帐户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60065616/

相关文章:

python - 需要帮助了解 Restful API 中的 SQL 注入(inject)漏洞

Python 对文件中的唯一名称进行排序和计数

html - Outlook 2007、2010 和 2013 中的响应式 2 列到 1 列电子邮件

python - Psycopg2 - 属性错误 : 'NoneType' object has no attribute 'fetchall'

python - 多个进程异步读取同一管道

python - 查找列表中两个标签之间的元素

python - 根据函数名称字符串执行函数

c# - 相当于使用 Outlook DASL 筛选器选择位置

c# - 从 Outlook 中检索单个项目的最有效方法是什么(互操作)

python - 如何创建一个小的 python 代码来获取团队通话的参与者列表?