Search code examples
pythonpython-3.xemailemail-attachmentssmtplib

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?


Solution

  • 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)