问题描述
我正在尝试通过电子邮件发送2个文件(Excel和PDF),但接收者仅获得.bin扩展名。 这是我的工作代码:
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import mimetypes
def get_att_mime(path):
mimetypes.init()
mimetype,_ = mimetypes.guess_type(path)
if mimetype is None:
print("on a pas trouvé de bon MIME,risque de problème d'extension à l'arrivée du mail !!!")
mimetype = 'application/octet-stream'
type_,_,subtype = mimetype.partition('/')
att_mime = MIMEBase(type_,subtype)
return att_mime
def create_mime(d):
mime_multipart = MIMEMultipart()
mime_multipart['From'] = d["From"]
mime_multipart['To'] = d["To"]
mime_multipart['Subject'] = d["Subject"]
mime_multipart.attach(MIMEText(d["msg"]))
return mime_multipart
def add_file_list(mime,file_path_list=[]):
[add_file(mime,file_path) for file_path in file_path_list]
def add_file(mime,file_path):
attachment = open(file_path,"rb")
att_mime = get_att_mime(file_path)
att_mime.set_payload(attachment.read())
# encode into base64
encoders.encode_base64(att_mime)
att_mime.add_header('Content-disposition',"attachment; filename= %s" % file_path)
mime.attach(att_mime)
"""
def add_file(mime,file_path):
print(get_attachment_from_path(file_path))
attachment = open(file_path,"rb")
p = MIMEBase('application','octet-stream')
p.set_payload(attachment.read())
# encode into base64
encoders.encode_base64(p)
p.add_header('Content-disposition',"attachment; filename= %s" % file_path)
mime.attach(p)
"""
def create_smtp_session(d):
s = SMTP('smtp.gmail.com',587)
# start TLS for security
s.starttls()
s.login(d["From"],d["sender_password"])
return s
def send_mail(d):
mime = create_mime(d)
add_file_list(mime,d["filename_list"])
try:
s = create_smtp_session(d)
s.sendmail(d["From"],d["To"],mime.as_string())
except Exception as e:
print(e)
print("échec de l'envoi de mail")
print(d)
return -1
s.quit()
print("envoi de mail réussi")
return 0
if __name__ == "__main__":
d = {
"From": "YOUREMAIL.com","To": "FINALUSEREMAIL.fr","Subject": "Sujet du mail","sender_password": "YOUREMAILPASSWORD","msg": "Bonjour,\n\nTexte du message.\n\nCordialement,","filename_list": ["model.xlsx","model.pdf"]
}
state = send_mail(d)
如果我发送简单文档,它就像一个超级按钮,但是当我发送经过修改(使用openpyxl)的Excel和基于此Excel创建的pdf时,接收者得到的扩展名为.bin而不是。 xlsx和.pdf。 我不知道它来自哪里,我想这是一个Mime问题(解码器/编码器),但是我没有收到任何警告。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)