[英]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.