开发者

MIME Header in message when sending e-mail with Python

开发者 https://www.devze.com 2023-02-18 22:31 出处:网络
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开发者_Go百科 this really ugly header in the body of the message (As

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开发者_Go百科 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. 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. Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消