1

I am trying to send an email with an attachment from my Python script. To send the text in the body seems ok but I am not sure about the syntax for the file attachment.

My code snippet is:

import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_email(self):
    fromaddress = "rladhani@gmail.com"
    toaddress = "riaz.ladhani@company.com"
    text = "subject line test"
    username = "rladhani@gmail.com"
    password = "-"
    msg = MIMEMultipart()
    msg['from'] =fromaddress
    msg['to'] = toaddress
    msg['subject'] = text
    msg.attach(MIMEText (text))
    attachment = open(r"C:\Webdriver\ClearCoreRegression Test\TestReport\TestReport_01052016.html", "rb")

    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

    msg.attach(part)
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(username, password)
    server.sendmail(fromaddress, toaddress, msg.as_string())
    server.quit()

How can I add the file attachment to the email? Also I am getting an unresolved reference error on

encoders.encode_base64(part)

Thanks, Riaz

Riaz Ladhani
  • 3,946
  • 15
  • 70
  • 127

1 Answers1

4

Looks like this one has been asked a few times.

How to send email attachments with Python

How do I send an email with a .csv attachment using Python

Sending Email attachment (.txt file) using Python 2.7 (smtplib)

Hope these help!

Community
  • 1
  • 1
A. Campbell
  • 404
  • 2
  • 12