简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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