我想通过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(),一切正常。
答案 0 :(得分:0)
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"