问题描述
我正在尝试通过python发送邮件和附件(.pdf文件)。 邮件已发送,但附件变成了未知附件而不是.pdf文件
我的代码如下:
import smtplib
import os
import ssl
import email
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
port = 465
smtp_server = "smtp.gmail.com"
subject = "An example of txt.file"
sender = "..."
receiver = "..."
password = "..."
message = MIMEMultipart()
message["From"] = sender
message["To"] = receiver
message["Subject"] = subject
filename = '318.pdf'
attachment = open(filename,"rb")
part = MIMEBase("application","octet-stream")
part.set_payload(attachment.read())
part.add_header('Content disposition','attachment',filename=filename)
encoders.encode_base64(part)
message.attach(part)
message.attach(part)
body = "This is an example of how to send an email with an .pdf-attachment."
message.attach(MIMEText(body,'plain'))
text = message.as_string()
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com",port,context=context) as server:
server.login(sender,password)
server.sendmail(sender,receiver,text)
print('Sent')
它有什么问题,或者我必须做些什么?
我尝试了不同的文件类型,.pdf文件位于python文件目录中,...
解决方法
你写了
part.add_header('Content Disposition','attachment',filename=filename)
但是'filename'参数名必须作为字符串提供,并且您也错过了'Content-Disposition'中的连字符。试试
part.add_header('Content-Disposition','attachment; filename=' + filename)
这应该可以解决您的问题。只需指出,您将“ part”附加了两次-在第20和22行。
我认为您可能已经在关注this文章。但是,如果没有,我想您会发现它很有用。