我在outlook上有两个帐户'user1@example.com‘和'user2@example.com’。我在user1 draft文件夹中有许多草稿,希望在发送之前将每封电子邮件更新到user2地址,以便user2成为电子邮件的发件人,并显示在邮件项目的发件人字段中。
使用exchangelib,我成功地将发件人和帐户地址从user1改为user2 (甚至是print(item.sender, item.account)来验证更改),但更新完成后,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()发布于 2020-02-06 14:36:02
您需要对项目调用.save(),而不是对文件夹调用。Folder.save()用于更改文件夹本身的属性,例如文件夹名称。
按照另一个答案中的建议打印项目只会告诉您项目的本地副本已更改,而不是服务器上的实际项目。您需要调用item.refresh()来查看实际更新的内容(尽管当您调用item.save()时,这应该总是匹配的)。
最后,item.account是对Account对象的引用。不要改变这一点。包含发件人信息的两个字段是item.sender和item.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发布于 2020-02-05 18:21:06
不是一个真正的解决方案,而是一些你可以寻找的东西:
您可以执行以下操作:
for item in user_account.drafts.all().order_by('subject'):
print(item) #Copy Text into Notepad++ and search for user1/ user1@example.com
item.sender = 'user2@example.com'
item.account = 'user2@example.com'
user_account.drafts.save(update_fields=['sender', 'account'])
print(item) #Copy Text in another Notepad++ tab to see if every user1 entry has been replaced
exit("Done")您应该能够比较.txts并找到缺少的项目(如果有)警告:根据邮件数量的不同,将出现巨大的文本墙
https://stackoverflow.com/questions/60065616
复制相似问题