[英]Can't send an attachment to my email using smtplib
我正在尝试使用smtplib
库将 csv 文件发送到我的 email 地址。 当我运行下面的脚本时,它发送 email 没有任何问题。 但是,当我打开那个 email 时,我可以看到那里没有附件。
我试过:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
attachment = "outputfile.csv"
msg = MIMEMultipart()
msg['Subject'] = "Email a csv file"
msg['Body'] = "find the attachment"
msg['From'] = "someemail@gmail.com"
msg['To'] = "anotheremail@gmail.com"
part = MIMEBase('application', "octet-stream")
part.set_payload(open(attachment, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=attachment)
msg.attach(part)
msg = f"Subject: {msg['Subject']}\n\n{msg['Body']}"
with smtplib.SMTP('smtp.gmail.com',587) as server:
server.ehlo()
server.starttls()
server.ehlo()
server.login('someemail@gmail.com','ivfpklyudzdlefhr')
server.sendmail(
'someemail@gmail.com',
'anotheremail@gmail.com',
msg
)
将 csv 文件发送到我的 email 应该带来哪些可能的变化?
代码需要两处改动
msg = f"Subject: {msg['Subject']}\n\n{msg['Body']}"
正在用字符串覆盖消息 object msg
。 它不是必需的,可能会被删除。
要发送消息 object(而不是字符串),请使用SMTP.send_message
。
这段代码应该可以工作:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
attachment = "outputfile.csv"
msg = MIMEMultipart()
msg['Subject'] = "Email a csv file"
msg['Body'] = "find the attachment"
msg['From'] = "someemail@gmail.com"
msg['To'] = "anotheremail@gmail.com"
part = MIMEBase('application', "octet-stream")
part.set_payload(open(attachment, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=attachment)
msg.attach(part)
with smtplib.SMTP('smtp.gmail.com',587) as server:
server.ehlo()
server.starttls()
server.ehlo()
server.login('someemail@gmail.com','ivfpklyudzdlefhr')
server.send_message(msg)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.