无法发送整封电子邮件 - smtp

Not being able to send the whole email - smtp

sent_subject = "Warning"
sent_body = (
             "Hey"
             "For game ID: {} and game Name: {} \n\n you are going to die in {}sec"
             "\n\n"
             "Warning,\n"
             "Chixcy\n".format(game_id, game_name, secs))

smtp_server.sendmail(sender_add,receiver_add,sent_body)

我收到的邮件是you are going to die in 30sec Warning Chixcy

我想连同主题一起得到全身

那是因为前几行应该是电子邮件 headers。您也永远不会在任何地方使用您的主题 - 这可能是一个提示。

因此我们需要

from email.mime.text import MIMEText
message = MIMEText(sent_body, 'plain')
message["From"] = sender_add
message["To"] = receiver_add
message["Subject"] = sent_subject

那么当你使用 .sendmail 时,你必须:

smtp_server.sendmail(sender_add, receiver_add, message.as_string())

注意:还有更方便的(更多human-friendly)类来处理邮件(例如Python3.6引入的email.message.EmailMessage),但是作为我自 Python 3.4 以来,我主要处理多部分电子邮件,纯 MIME 消息是我的方式。