简体   繁体   English

使用Python发送电子邮件时消息中的MIME标头

[英]MIME Header in message when sending e-mail with Python

So I am trying to send out an email using this template and using a log file as the body, the email gets sent fine. 因此,我尝试使用此模板并使用日志文件作为正文来发送电子邮件,但电子邮件发送得很好。 However, it has this really ugly header in the body of the message (As seen below) 但是,它在邮件正文中确实有这个丑陋的标头(如下所示)

From nobody Thu Mar 17 14:13:14 2011
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

Is there anyway to make it so the message does not include the header above? 无论如何,它使消息不包括上面的标头? Thank you! 谢谢!

#!/usr/bin/python
import smtplib
import time
import datetime
from email.mime.text import MIMEText
today = datetime.date.today()
textfile = "/home/user/Public/stereo-restart-log"
FROM = "my-username"
TO = ["recipients"]

SUBJECT = "Stereo log: %s" % today
fp = open(textfile, 'rb')
TEXT = MIMEText(fp.read())
fp.close()
message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, TO, SUBJECT, TEXT)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('my-username','mypass')
server.sendmail(FROM, TO, message)
server.close()

With MIMEText you have already created the message object. 使用MIMEText,您已经创建了消息对象。 You just need to add the proper headers to it: 您只需要添加适当的标题即可:

FROM = "my-username"
TO = ["recipients"]
SUBJECT = "Stereo log: %s" % today
fp = open(textfile, 'rb')
TEXT = MIMEText(fp.read())
fp.close()
TEXT['From'] = FROM
TEXT['To'] = ",".join(TO)
TEXT['Subject'] = SUBJECT
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('my-username','mypass')
server.sendmail(FROM, TO, TEXT.as_string)
server.close()

Note that you can must convert the TO list to string before adding as header, because the square brackets are not allowed in the To/From headers. 请注意,在添加为标题之前,您必须先将TO列表转换为字符串,因为To / From标题中不允许使用方括号。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM