简体   繁体   English

无法使用 smtplib 向我的 email 发送附件

[英]Can't send an attachment to my email using smtplib

I'm trying to send a csv file to my email address using smtplib library.我正在尝试使用smtplib库将 csv 文件发送到我的 email 地址。 When I run the script below, it sends the email without any issues.当我运行下面的脚本时,它发送 email 没有任何问题。 However, when I open that email I could see that there is no attachment in there.但是,当我打开那个 email 时,我可以看到那里没有附件。

I've tried with:我试过:

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?将 csv 文件发送到我的 email 应该带来哪些可能的变化?

The code needs two changes代码需要两处改动

  1. msg = f"Subject: {msg['Subject']}\n\n{msg['Body']}" is overwriting the message object msg with a string. msg = f"Subject: {msg['Subject']}\n\n{msg['Body']}"正在用字符串覆盖消息 object msg It is not required and may be deleted.它不是必需的,可能会被删除。

  2. To send a message object (as opposed to a string), use SMTP.send_message .要发送消息 object(而不是字符串),请使用SMTP.send_message

This code ought to work:这段代码应该可以工作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM