我制作了一个简单的烧瓶api,用于侦听JSON帖子,解析包含图像的URL,最后将此图像附加到电子邮件中并发送电子邮件。这是为每个传入的JSON帖子触发一个唯一的电子邮件..它在第一个请求时工作正常,图像按预期附加,电子邮件被发送和接收....但是当下一个POST到来时,附件来自以前的电子邮件没有清理过#34;并且随后的电子邮件中包含旧附件..这将永远持续下去。
所以我的问题是,如何在每次POST后清理电子邮件正文,附件等?
我尝试在"最后"添加内容。阻止,例如清除正文电子邮件正文变量等。但我不确定这是否是正确的方法,所以我想我会问这里
这是代码。它应该是非常不言自明的我希望(缩进搞砸了)。 #!/ usr / bin / env python3 来自flask进口烧瓶 来自烧瓶导入请求,会话 import urllib.request 进口时间
verbose = True
email_notify = True
webdav_path = '/var/www/webdav/'
def fetch_image(url, urldir):
""" Fetch string after delimiter (webdir/) """
return url.partition(urldir)[2]
if email_notify:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
strFrom = 'xxx@xxx.xxx'
strTo = 'xxx@xxx.xxx'
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
app = Flask(__name__)
@app.route('/alert', methods = ['POST'])
def postJsonHandler():
print ('Is json? ',request.is_json) if verbose else None
alert_localtime = time.strftime("%Y-%m-%d %H:%M")
d = request.get_json()
chart_url = d['imageUrl']
if email_notify:
if chart_url:
if:
chart_png = fetch_image(chart_url,'/webdav/')
final_image = webdav_path + chart_png
else:
print('No image found in POST, so nothing to attach')
try:
msgRoot.preamble = 'multi part message'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('Alternative plain text message.')
msgAlternative.attach(msgText)
mail_body = """\
<p>Alert for: """ + alert_title + """<br>
<br>
Alert trigged at: """ + alert_localtime + """.<br>
Alert reason: """ + 'somereason' + """.<br>
<br>
Graph:<br>
<br>
<img src="cid:image1">
</p>
"""
msgText = MIMEText(mail_body, 'html')
msgAlternative.attach(msgText)
fp = open(final_image, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
smtp = smtplib.SMTP()
smtp.connect('localhost')
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
print ("Successfully sent email"):
except:
pass)
finally:
??
return 'JSON posted'
app.run(host='127.0.0.1', port= 8091, debug=True)