首页 > 解决方案 > Python:将 .txt 附加到电子邮件

问题描述

我做了一些谷歌研究,发现了很多东西。不幸的是,我不明白我发现了什么,所以我需要打开一个新的“公共请求”。正如我在标题中所说的那样,我想在我的电子邮件中附加一个 .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))

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

标签: pythonemailattachment

解决方案


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

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

推荐阅读