【问题标题】:Attaching file in Python email在 Python 电子邮件中附加文件
【发布时间】:2015-07-30 15:02:32
【问题描述】:

所以我尝试了多种方法来将文件(特别是 CSV 文件)附加到 python 中的电子邮件并发送。我的文本电子邮件工作正常,我确实收到了一个 CSV 文件,只是一个空文件。我目前正在发送我的附件,如下所示:

ctype, encoding = mimetypes.guess_type("results.csv")
if ctype is None or encoding is not None:
    ctype = "application/octet-stream"

maintype, subtype = ctype.split("/", 1)

# organizing receivers
receiver = receivers.split(',')

# creating subject
subject = 'BLAH BLAH'
timestamp = time.strftime("%m/%d/%Y:%H:%M:%S")
subject += str(timestamp)

# form email
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = " ".join(receivers)
msg['Subject'] = subject
msg['Message-Id'] = make_msgid()
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(msgstr, 'plain'))

if maintype == "text":
    fp = open("results.csv")
    attachment = MIMEText(fp.read(), _subtype=subtype)
    fp.close()

else:
    fp = open('results.csv', "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)

attachment.add_header("Content-Disposition", "attachment", filename='results.csv')
msg.attach(attachment)

try:
    smtpobj = smtplib.SMTP('smtp.gmail.com:587')
    smtpobj.ehlo()
    smtpobj.starttls()
    smtpobj.ehlo()
    smtpobj.login(username, password)

    smtpobj.sendmail(sender, receiver, msg.as_string())
    smtpobj.quit()

except smtplib.SMTPException:
    print 'Error: unable to send mail'

这与此处的答案相似:python can't send attachment files through email 我也尝试过更简单的方法,类似于: How to send email attachments with Python https://docs.python.org/2/library/email.html

和其他人,但没有成功。如何发送完整的附件?

【问题讨论】:

    标签: python mime


    【解决方案1】:

    所以经过多次调试后,我意识到我没有正确关闭文件,然后再尝试再次阅读以撰写电子邮件。我有类似下面的代码:

    with open('results.csv', "rb") as csvfile:
        #compose the csv file
        #blah
        #blah
        #blah
        #then I called my email function but the file hadn't yet been closed and I was trying to reopen.
    

    为了解决这个问题,我只是简单地在 with 语句之外调用我的电子邮件函数来关闭文件。

    with open('results.csv', "rb") as csvfile:
            #compose the csv file
            #blah
            #blah
            #blah
    
    send_the_email()
    

    我希望这可以防止其他人像我一样在如此简单的事情上浪费太多时间。

    【讨论】:

      【解决方案2】:

      尝试编辑此部分

      else:
          with open('results.csv', "rb") as fp:
              fp.seek(0)
              attachment = MIMEBase(maintype, subtype)
              attachment.set_payload(fp.read())
              encoders.encode_base64(attachment)
      

      【讨论】:

      • 我试过了,不幸的是仍然收到空的附件 (0 kb)。 fp 之后缺少分号,但这并不重要。
      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-28
      • 2012-09-07
      • 1970-01-01
      • 2014-06-25
      相关资源
      最近更新 更多