使用python从文件和自定义内容中嵌入内容来发送邮件

时间:2018-07-14 09:17:05

标签: python email smtp

我有一个文件,其中包含命令的某些输出。我希望将此文件以及自己的自定义内容添加到电子邮件正文中并发送。我尝试使用以下代码,但仅发送了其中一个内容。

#!/app/dev/Python/bin/python3
strFrom = 'test@test.com'
strTo = ['abc@xyz.com']  
topcommand = "top -b -d 5 | head -n 12 > top.txt"
subprocess.Popen(topcommand, shell=True,stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip()
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'Notification'
msgRoot['From'] = strFrom
msgRoot['To'] = ", ".join(strTo)
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
top_file = open('top.txt','rb')
alert_msg = MIMEText(top_file.read().encode("utf-8"), 'plain', 'utf-8')
top_file.close()
msgText = MIMEText('<b>Update</b><br><br>File generated.<br><br><b>TOP Command Snapshot</b><br><br><br>Thanks<br>', 'html')
msgAlternative.attach(msgText)
final = msgText + alert_msg
smtp = smtplib.SMTP("xxx.xxx.com", xx, timeout=120)
smtp.sendmail(strFrom, strTo, final.as_string())
smtp.close()

我要接收的邮件格式的正文应为-

 File generated.

TOP Command Snapshot

<output from the top.txt file>

Thanks.

有人可以帮我吗?我尝试了各种方法,但是不知何故。

0 个答案:

没有答案