【发布时间】:2020-11-26 15:52:09
【问题描述】:
作为更大工作流程的一部分,我获得了电子邮件和密码,以及该证书的 .pfx 证书和密码。我需要使用它们来下载特定的电子邮件(特别是其附件),以便可以在其他脚本中进行处理。
我已经设法将 .pfx 文件转换为 .pem 文件。使用下面的代码,我可以下载消息:
import email
import imaplib
EMAIL = 'test@test.com'
PASSWORD = 'testpassword'
SERVER = "outlook.office365.com"
# Connect to the server and go to its inbox
mail = imaplib.IMAP4_SSL(SERVER, port=993)
mail.login(EMAIL, PASSWORD)
mail.select('inbox')
# Get the relevant mail ID
status, ids = mail.search(None, '(HEADER Subject "Testmessage_")')
mail_id = ids[0].split()[0]
# Fetch the mail, get the data, write the file
status, contents = mail.fetch(mail_id, '(RFC822)')
data = contents[0][1]
with open("outputfile.txt", "wb") as outputfile:
outputfile.write(data)
然后我可以使用以下命令使用 OpenSSL 解码 outputfile.txt:
openssl cms -decrypt -in outputfile.txt -inkey cert.pem > outputmessage.txt
我可以确认在 outputmessage.txt 文件中,附件的内容是可见的,并且通过一些解决方法,可以在我的 Python 脚本的其余部分中使用。
但是,这意味着使用多个临时文件和(至少)三个不同的命令(再次是 python - openssl - python)。我想在 Python 中完成所有这些操作,因此我不必创建临时文件,并且可以立即在以下脚本中处理结果。 此外,我更愿意使用尽可能少的外部依赖项。
我已经看到提到 M2Crypto 和密码学,但我似乎无法让任何一个包在我的机器上工作(有轮子的东西?)。还有其他选择吗?
【问题讨论】:
标签: python python-3.x pem imaplib