gpt4 book ai didi

Python sendmail 与文本文件内容

转载 作者:太空宇宙 更新时间:2023-11-03 18:58:17 25 4
gpt4 key购买 nike

我想通过 python 脚本发送邮件,我需要它来提醒我一些丢失的文件。

scripy 必须读取日志文件(*.txt)并将该文件的内容发送到我的邮件中,所以我做到了:

import smtplib, os
from email.mime.text import MIMEText


raport_file = open('alert.txt','rb')
alert_msg = MIMEText(raport_file.read().encode("utf-8"), 'plain', 'utf-8')
raport_file.close()




m = smtplib.SMTP()
m.connect("*****", 25)
m.sendmail("Check_Files", "*****", alert_msg.as_string())
m.quit()

脚本运行,但根本没有邮件。如果我用“任何文本”替换alert_msg.as_string(),一切正常。

最佳答案

import smtplib
import base64
import os
import sys

FROM = 'user@user.com'
TO = 'user@user.com'
MARKER = 'SIMPLE_MARKER_GOES_HERE'

if __name__ == "__main__":
filename = 'name_of_file'

# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
filename = os.path.basename(filename)

body ="""
Insert whatever message you want here or dynamically create.
"""

# Define the main headers.
part1 = """From: Matt Vincent <matt.vincent@jax.org>
To: %s
Subject: Sending Attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (TO, MARKER, MARKER)

# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body, MARKER)

# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" %(filename, filename, encodedcontent, MARKER)

message = part1 + part2 + part3

try:
smtpObj = smtplib.SMTP('domainhere')
smtpObj.sendmail(FROM, TO, message)
print "Successfully sent email"
except Exception:
print "Error: unable to send email"

关于Python sendmail 与文本文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16734000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com