【问题标题】:Python: attach .txt to an emailPython:将 .txt 附加到电子邮件
【发布时间】:2019-09-13 19:13:02
【问题描述】:

我做了一些谷歌研究,发现了很多东西。不幸的是,我不明白我发现了什么,所以我需要打开一个新的“公共请求”。正如我在标题中所说的,我想在我的电子邮件中附加一个 .txt 文件。很抱歉在成千上万的人已经这样做之后再次问这个问题,但这是我发送邮件的方法:

import smtplib, ssl
from email.mime.multipart import MIMEMultipart
from email.mime.multipart import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
import config

#creating file to write the keys in later
file = open("my_filename.txt", "w+")

#creating subject and message for the email
subject = "Test123 new / updated"
msg = "look in attachment"

def send_mail(subject, msg)
    try:
        server = smtplib.SMTP("smtp.gmail.com:587")
        server.ehlo()
        server.starttls()
        server.login(config.EMAIL_ADDRESS, config.PASSWORD)
        message = "Subject: {}\n\n{}".format(subject, msg)
        server.sendmail(config.EMAIL_ADDRESS, config.EMAIL_RECEIVER, message)
        server.quit()
        print("success: Email sent!")
    except:
        print("Email failed to send")

这对我来说效果很好(只是通过一些研究来管理它。最后我发现了类似的文件:

msg = MIMEMultipart()
#some other code to create a mail with subject and stuff like that
msg.attach(MIMEText(text))

如果我将“text”更改为“my_filename.txt”,它将不起作用。我需要改变什么?

【问题讨论】:

标签: python email attachment


【解决方案1】:

啊,我有另一个自己的想法。我删除了“msg =”查看附件“”这一行,而不是使用方法 file.read()。所以我发送邮件的线路现在看起来像这样:

server.sendmail(config.EMAIL_ADDRESS, config.EMAIL_RECEIVER, file.read())

【讨论】:

  • 它现在不是文件,但文本作为普通消息在邮件正文中发送。我也可以和这个一起工作
猜你喜欢
  • 1970-01-01
  • 2014-06-25
  • 1970-01-01
  • 1970-01-01
  • 2019-06-05
  • 1970-01-01
  • 2014-08-15
  • 1970-01-01
相关资源
最近更新 更多