MITHU
MITHU

Reputation: 164

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'] = "[email protected]"
msg['To'] = "[email protected]"

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('[email protected]','ivfpklyudzdlefhr')
    server.sendmail(
        '[email protected]',
        '[email protected]',
        msg
    )

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

Upvotes: 0

Views: 4106

Answers (1)

snakecharmerb
snakecharmerb

Reputation: 55933

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'] = "[email protected]"
msg['To'] = "[email protected]"

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('[email protected]','ivfpklyudzdlefhr')
    server.send_message(msg)

Upvotes: 5

Related Questions