简体   繁体   中英

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. When I run the script below, it sends the email without any issues. However, when I open that email I could see that there is no attachment in there.

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?

The code needs two changes

  1. msg = f"Subject: {msg['Subject']}\n\n{msg['Body']}" is overwriting the message object msg with a string. It is not required and may be deleted.

  2. To send a message object (as opposed to a string), use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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