我正在尝试使用Python通过gmail发送电子邮件。我能够创建成功发送的基本电子邮件。当我尝试通过此电子邮件发送附件时,我的代码崩溃了,我也不明白为什么。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("EMAIL", "PASSWORD")
msg = MIMEMultipart()
body = "Body_of_the_mail"
msg.attach(MIMEText(body, 'plain'))
# open the file to be sent
filename = "FILENAME_WITH_EXTENSION"
attachment = open("FILEPATH", "rb")
# instance of MIMEBase and named as p
p = MIMEBase('application', 'octet-stream')
# To change the payload into encoded form
p.set_payload((attachment).read())
# encode into base64
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
# attach the instance 'p' to instance 'msg'
msg.attach(p)
server.sendmail("SENDER", "RECEIVER", msg)
server.quit()