Python Smtplib 电子邮件(错误的主题和消息字段)

Python Smptlib Email (Wrong subject & message field)

每次我使用此功能发送电子邮件时,它不会将主题和消息添加到正确的字段,而是将其添加到 'from:' 或其他内容。 Here's the image of it. 知道如何解决这个问题吗?谢谢回答

import smtplib

## NON-ANONYMOUS EMAIL
def email():
    # Parts of an email
    SERVER = 'smtp.gmail.com'
    PORT = 587
    USER = 'something@gmail.com'
    PASS = 'something'
    FROM = USER
    TO = ['something@riseup.net']
    #SUBJECT = 'Test'
    MESSAGE = 'Test message.'

    # Connects all parts of email together
    message = "From: %s\r\n To: %s\r\n %s" % (FROM, ", ".join(TO), MESSAGE)

    # Sends an email
    email = smtplib.SMTP()
    email.connect(SERVER,PORT)
    email.starttls()
    email.login(USER,PASS)
    email.sendmail(FROM, TO, message)
    email.quit()

email()

\r\n 后不能有 space。电子邮件 header 行通过缩进继续,因此您的代码创建了一个非常长的 From: header,其中包含您尝试放入不同字段的所有数据。

无论如何,手动将纯文本片段粘合在一起是一种非常粗糙且 error-prone 构建电子邮件的方法。您很快就会发现无论如何您都需要 Python email 模块的各种功能(传统电子邮件仅是 7 位单部分 ASCII;您可能需要一个或多个附件、内容编码、字符集支持、多部分消息或许多其他 MIME 功能之一)。这也巧合地提供了更好的文档来说明如何正确创建一个普通的电子邮件消息。

根据@tripleee 建议使用 email 模块,这是一个使用您当前代码的基本示例:

import smtplib
from email.mime.text import MIMEText

## NON-ANONYMOUS EMAIL
def email():
    # Parts of an email
    SERVER = 'smtp.gmail.com'
    PORT = 587
    USER = 'something@gmail.com'
    PASS = 'something'
    FROM = USER
    TO = ['something@riseup.net']
    SUBJECT = 'Test'

    # Create the email
    message = MIMEText('Test message.')
    message['From'] = FROM
    message['To'] = ",".join(TO)
    message['Subject'] = SUBJECT

    # Sends an email
    email = smtplib.SMTP()
    email.connect(SERVER,PORT)
    email.starttls()
    email.login(USER,PASS)
    email.sendmail(FROM, TO, message.as_string())
    email.quit()

请注意,使用 keys 定义电子邮件的各个部分比 message['Subject'] 更容易,而不是尝试构建字符串或 'gluing parts together' tripleee 把它。

您可以访问的不同字段(发件人、收件人、主题等)在 RFC 2822 - Internet Message Format 中定义。

这些文档不容易阅读,所以这里列出了一些您可以使用的字段键:ToFromCcBcc, Reply-To, Sender, Subject.

You cannot have a space after the \r\n. An email header line is continued by indenting it, so your code is creating a really long From: header with all the data you are trying to put in different fields.

正如 triplee 和 RFC-2822 文档所说,如果您想手动构建电子邮件字符串,请查看该文档中类似于此示例的字段定义:

from = "From:" mailbox-list CRLF

在构建电子邮件字符串时,您可以将其转换为 Python 代码:

"From: something@riseup.net \r\n"

我能够让我的工作使用: ("来自: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % (gmail_user, 收件人, 主题, 正文))