python - 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”,它就不起作用。我需要改变什么?
解决方案
啊,我有另一个自己的想法。我删除了“msg =”查看附件“”这一行,而不是使用方法 file.read()。所以我发送邮件的线路现在看起来像这样:
server.sendmail(config.EMAIL_ADDRESS, config.EMAIL_RECEIVER, file.read())
推荐阅读
- c# - 为什么我不能在两个事件中调用表单对象?
- c# - 合并多个内容中的所有内容
div内的标签,变成单个字符串
- java - 如果我初始化一个已经在 JAVA 中初始化的 Class 对象会发生什么?
- terraform - 展平复合地图的输出内容
- python - Excel列数据需要转换成双引号括起来的值列表,然后通过排除开始括号写入json文件
- php - 在 codeigniter 中加入超过 2 个数据库表错误:1066
- azure - 如何在通过 webhook 调用 azure 自动化 runnbook 的 azure 函数中获取响应
- linux - 使用linux命令列出给定小时内目录中的文件
- unix - 使用 SFTP 以二进制模式将大型机文件下载到 Unix
- haskell - 箭头 (->) 作为 haskell 数据构造函数