首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将msg中的附件附加到Mime中,以便在Python中作为电子邮件发送?

如何将msg中的附件附加到Mime中,以便在Python中作为电子邮件发送?
EN

Stack Overflow用户
提问于 2021-08-09 15:06:31
回答 2查看 105关注 0票数 0

我想打开一个.msg文件,获取附件,并将它们发送到特定的邮件地址。我使用extract_msg,我似乎不能只将.msg中的附件附加到我的邮件中。

到目前为止,我所拥有的:

代码语言:javascript
运行
复制
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()

我得到了错误:

代码语言:javascript
运行
复制
     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'

我写信给temp的唯一原因是,似乎不可能只将原始.msg的附件附加到Mime上。

欢迎任何帮助,有错误或更好的方法来处理附件。

编辑:堆栈跟踪:

代码语言:javascript
运行
复制
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'
EN

回答 2

Stack Overflow用户

发布于 2021-08-10 09:55:06

目前还不清楚Message()部件从何而来,也不清楚它到底是做什么的。我将假设它如您所希望的那样工作,并推测您可能是Outlook的受害者,幸运的是找到了一个可以处理其专有消息的库。

您的代码有两个有问题的流程:即使没有提取附件,它也会发送电子邮件;即使连接到SMTP服务器失败,它也会尝试发送。您想要将这些重构为类似于

代码语言:javascript
运行
复制
else:
    print("No attachments")
    sys.exit(0)

在没有提取任何东西的时候退出,并且

代码语言:javascript
运行
复制
try:
    server.login(email_sender, password)
except:
    print(f"Login failed for user: {email_sender}\nWith password: {password}")
    sys.exit(1)

在无法继续时退出并返回错误(或者干脆取出try / except并让脚本崩溃并进行回溯;如果它仅供您个人使用,这可能是可以接受的,而且当您看到调试信息时也更容易进行调试)。

(这不是一个恰当的答案,但我觉得我也需要指出这些问题。)

票数 1
EN

Stack Overflow用户

发布于 2021-08-10 07:19:04

好了,伙计们,这就是我的工作原理:

代码语言:javascript
运行
复制
def send_mails_from_msg(attachment, send_to, path):
  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 = 'mailsender123@gmail.com'
  password = 'XXXXXX'

  print("----------------------------------------------------------------------------------------------------")
  print(f"Send to: {send_to}\nAttachement: {attachment}\n")

  msgMime = MIMEMultipart()
  msgMime['From'] = msg_sender
  msgMime['To'] = send_to
  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:
      for x in msg.attachments:
          x.save(customPath=attachments_dir)
      for files in os.listdir(attachments_dir):
          print(f"Files: {files}")
          attachment = open(f"{attachments_dir}/{files}", 'rb')
          part.set_payload(attachment.read())
          encoders.encode_base64(part)
          part.add_header('Content-Disposition', "attachment; 

附件%s“% filename= )msgMime.attach(零件)

代码语言:javascript
运行
复制
  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, text)
  server.quit()

现在这个用邮件发送jpg,任务完成了!但是...附件看起来像这样:__io.BufferedReader name='resources_attachments_image001.jpg'_,它注册为附件,但不能打开...我现在正在试着解决这个问题

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68714370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档