无法使用 smtplib 将附件发送到我的电子邮件

Can't send an attachment to my email using smtplib

我正在尝试使用 smtplib 库将 csv 文件发送到我的电子邮件地址。当我 运行 下面的脚本时,它发送电子邮件没有任何问题。但是,当我打开那封电子邮件时,我发现里面没有附件。

我试过:

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
    )

What possible change should I bring about to send a csv file to my email?

代码需要修改两处

  1. msg = f"Subject: {msg['Subject']}\n\n{msg['Body']}" 正在用字符串覆盖消息对象 msg。不需要,可以删除。

  2. 要发送消息对象(而不是字符串),请使用 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)