问题描述
这些是我用来发送电子邮件的邮件:
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
使用此功能向电子邮件添加附件以选择文件:
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()
)
问题在于,文件确实可以发送,但是它们似乎包裹在电子邮件附件的' '
中。它们看起来像这样:'document.pdf'
,使文档不可读,例如,由于它被包裹在' '
中,因此在电子邮件中没有说PDF File。
我已设法在计算机上打开文件,但无法在手机上打开它们。如何才能从文件名中删除' '
?我尝试做os.path.basename(file).strip("\'")
或.strip("'")
,但是' '
仍在包裹文件名。如何删除这些?
很乐意提供更多详细信息。
解决方法
将'application / pdf'设置为模仿类型可能会有所帮助-一些邮件客户端依靠模仿类型来确定应打开附件的应用程序。
# 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)
...