繁体   English   中英

无法使用 SMTPLIB 打开附件

[英]Can't open attachments using SMTPLIB

这些是我用来发送 email 的导入:

import tkinter as tk
from tkinter import filedialog
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import email, smtplib, ssl
from email import encoders
import os

我制作了一个脚本,您可以在其中使用tkfiledialog将附件添加到使用此 function 的 select 文件中:

def browse_file(): # Select a file to open
        global filelist

        filelist = filedialog.askopenfilenames()
        files_attached_tk.set("Files Attached: " + str(len(filelist)))

这是附加和发送文件的脚本部分:(For 和 With 在相同的缩进上)

for file in filelist:
            attachment_part = MIMEBase("application", "octet-stream")
            attachment_part.set_payload(open(file, "rb").read())
            encoders.encode_base64(attachment_part)
            attachment_part.add_header("Content-Disposition", "attachment; filename='%s'" % os.path.basename(file))
            message.attach(attachment_part)

# Create Server Connection
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
            server.login(config.email_sender, config.email_password)
            server.sendmail(
                sender_email, reciever_email, message.as_string()
            )

问题是,文件确实发送了,但是,它们似乎被包裹在 email 附件中' '中。 它们看起来像这样: 'document.pdf'这使得文档不可读,例如,它没有说 email 中的 PDF 文件,因为它被包裹在' '中。

我已经设法在我的电脑上打开这些文件,但我无法在我的手机上打开它们。 我怎样才能从文件名中删除' ' 我试图做os.path.basename(file).strip("\'").strip("'")' '仍在包装文件名。 我怎样才能删除这些?

很高兴提供更多细节。

将“应用程序/pdf”设置为 mimetype 可能会有所帮助 - 一些邮件客户端依赖 mimetype 来确定哪个应用程序应该打开附件。

# Additional imports

from email.mime.application import MIMEApplication
import mimetypes

...


for file in filelist:
    mimetype, _ = mimetypes.guess_type(file)
    mimetype = 'application/octet-stream' if mimetype is None else mimetype
    _, _, subtype = mimetype.partition('/')
    attachment_part = MIMEApplication(open(file, "rb").read(), subtype)
    attachment_part.add_header("Content-Disposition", "attachment; filename='%s'" % os.path.basename(file))
    message.attach(attachment_part)

...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM