python - 如何将 msg 中的附件附加到 Mime 以在 Python 中作为电子邮件发送?
问题描述
我想打开一个.msg
文件,获取附件,然后将它们发送到特定的邮件地址。我使用 extract_msg,我似乎无法仅将附件中的附件附加.msg
到我的邮件中。
到目前为止我所拥有的:
mail = f"{path}/{attachment}"
msg = extract_msg.Message(mail)
msg_sender = str(msg.sender)
msg_subj = str(msg.subject)
msg_message = str(msg.body)
email_sender = 'automailsender123@gmail.com'
password = 'XXX'
send_to_email = send_to
print("----------------------------------------------------------------------------------------------------")
print(f"Send to: {send_to}\nAttachement: {attachment}\n")
msgMime = MIMEMultipart()
msgMime['From'] = msg_sender
msgMime['To'] = send_to_email
msgMime['Subject'] = msg_subj
body = MIMEText(msg_message)
msgMime.attach(body)
resources_dir = "resources"
attachments_dir = os.path.join(resources_dir, "attachments")
part = MIMEBase('application', 'octet-stream')
if msg.attachments:
with tempfile.TemporaryDirectory() as tmp_dir_name:
for att in msg.attachments:
att_save_path = os.path.join(tmp_dir_name, att.longFilename)
att.save(customPath=tmp_dir_name)
attachment_stream = open(att_save_path, 'rb')
part.set_payload(attachment_stream.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % att_save_path)
msgMime.attach(part)
else: print("No attachments")
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
try:
server.login(email_sender, password)
except:
print(f"Login failed for user: {email_sender}\nWith password: {password}")
text = msgMime.as_string()
server.sendmail(email_sender, send_to_email, text)
server.quit()
我得到错误:
File "C:\Users\Kenneth.VanGysegem\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 596, in _rmtree_unsafe
with os.scandir(path) as scandir_it:
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\XXX.XXX\\AppData\\Local\\Temp\\tmpguckqnkr\\image001.jpg'
.msg
我写信给 temp 的唯一原因是,将原件的附件附加到 Mime似乎是不可能的。
欢迎任何帮助,包括错误或处理附件的更好方法。
编辑:堆栈跟踪:
Traceback (most recent call last):
File "C:\Users\Kenneth.VanGysegem\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 616, in _rmtree_unsafe
os.unlink(fullname)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\KENNET~1.VAN\\AppData\\Local\\Temp\\tmpguckqnkr\\image001.jpg'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Kenneth.VanGysegem\AppData\Local\Programs\Python\Python39\lib\tempfile.py", line 801, in onerror
_os.unlink(path)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\KENNET~1.VAN\\AppData\\Local\\Temp\\tmpguckqnkr\\image001.jpg'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Kenneth.VanGysegem\AppData\Local\Programs\Python\Python39\lib\tempfile.py", line 804, in onerror
cls._rmtree(path)
File "C:\Users\Kenneth.VanGysegem\AppData\Local\Programs\Python\Python39\lib\tempfile.py", line 812, in _rmtree
_shutil.rmtree(name, onerror=onerror)
File "C:\Users\Kenneth.VanGysegem\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 740, in rmtree
return _rmtree_unsafe(path, onerror)
File "C:\Users\Kenneth.VanGysegem\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 599, in _rmtree_unsafe
onerror(os.scandir, path, sys.exc_info())
File "C:\Users\Kenneth.VanGysegem\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 596, in _rmtree_unsafe
with os.scandir(path) as scandir_it:
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\KENNET~1.VAN\\AppData\\Local\\Temp\\tmpguckqnkr\\image001.jpg'
解决方案
目前尚不清楚这Message()
部分来自哪里或它究竟做了什么。我将假设它按您希望的那样工作,并推测您可能是 Outlook 受害者,他有幸找到了一个可以可接受地操纵其专有消息的库。
您的代码有两个有问题的流程:即使没有提取附件,它也会发送电子邮件,即使连接到 SMTP 服务器失败,它也会尝试发送。您想将这些重构为类似
else:
print("No attachments")
sys.exit(0)
在没有提取任何东西时退出,并且
try:
server.login(email_sender, password)
except:
print(f"Login failed for user: {email_sender}\nWith password: {password}")
sys.exit(1)
当您无法继续时退出并出现错误(或者只是取出try
/except
并让脚本崩溃并带有回溯;如果仅供您个人使用,这可能是可以接受的,并且在您看到调试信息时更容易调试)。
(不是一个正确的答案,但我觉得我也需要指出这些问题。)
推荐阅读
- java - 从另一个类的方法中调用 mutator
- python - Flask-SQLAlchemy:通过一对多关系获取父表中的列作为子模型属性
- python - Python:过滤数据帧,只保留 ActiveFlag 和日期的最后一个数据
- javascript - 如果匿名函数在循环中运行,是否会占用内存
- python - Pandas Dataframe 根据现有输入列导出新的计算列(不使用循环引用当前行和上一行)
- angular - Angular 中用于传递和显示数据的两个模型
- c# - 事件“未检查”以与“已检查”(哪些工作)不起作用的相同方式引发。WPF
- c# - 从 wav 流播放
- c - 如果将 BN_bn2bin 和 BN_bin2bn 应用于 RSA 密钥,为什么不给我相同的结果?
- python - 使用子进程控制 Minecraft 服务器