Python发送电子邮件但我的附件文件不起作用

时间:2016-05-01 17:19:49

标签: python python-2.7 selenium-webdriver pycharm

我正在尝试使用Python脚本中的附件发送电子邮件。 在正文中发送文本似乎没问题,但我不确定文件附件的语法。

我的代码段是:

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

如何将文件附件添加到电子邮件中? 另外我在

上得到了一个未解决的引用错误
encoders.encode_base64(part)

谢谢Riaz

1 个答案:

答案 0 :(得分:2)