如何使用Python和SMTP发送格式正确的电子邮件?

AKI*_*WEB 2 python email smtp

我正在尝试使用Python脚本发送电子邮件,但以某种方式希望我将其发送到我的邮箱中,而不是该格式。以下是我发送电子邮件的方法-

def send_mail(data):
    sender = 'fromuser@host.com'
    receivers = ['touser@host.com']

    message = """From: fromuser@host.com
    To: touser@host.com
    Subject: Send mail from python!!

    """
    body = 'Some Text\n'
    for item in data:
        body = body + '{name} - {res}\n'.format(name=item['name'], res=item['res'])

    message = message + body

    try:
       smtpObj = smtplib.SMTP('corp.host.com' )
       smtpObj.sendmail(sender, receivers, message)
       print "Mail sent"
    except smtplib.SMTPException:
       print "You can't spam. Mail sending failed!"
Run Code Online (Sandbox Code Playgroud)

这里的数据只有键-值对。

我在Outlook邮箱中收到这样的电子邮件-

From:我的前景部分中,下面的字符串是正确的,这是错误的-

fromuser@host.com To: touser@host.com Subject: Send mail from python!!
Run Code Online (Sandbox Code Playgroud)

并且To:Subject:部分即将显示为空,这也是错误的。

在正文中,我看到所有内容都在同一行中,但是我希望结果显示为-

Some Text

machinA - 0
machineB - 0
machineC - 0
Run Code Online (Sandbox Code Playgroud)

如何在Outlook邮箱中表示要显示的数据?

Max*_*Max 5

由于三引号会保留所有空格,因此您不小心发送了:

From: fromuser@host.com
      To: touser@host.com
      Subject: Send mail from python!!
Run Code Online (Sandbox Code Playgroud)

这将调用标题展开:缩进的行表示标题是连续的。因此,这确实是格式错误的From标头。您需要确保没有多余的空间。这可以解决您当前的示例:

def send_mail(data):
    sender = 'fromuser@host.com'
    receivers = ['touser@host.com']

    message = """\
From: fromuser@host.com
To: touser@host.com
Subject: Send mail from python!!
"""
    body = '\n\nSome Text\n'
    for item in data:
        body = body + '{name} - {res}\n'.format(name=item['name'], res=item['res'])

    message = message + body

    try:
       smtpObj = smtplib.SMTP('corp.host.com' )
       smtpObj.sendmail(sender, receivers, message)
       print "Mail sent"
    except smtplib.SMTPException:
       print "You can't spam. Mail sending failed!"
Run Code Online (Sandbox Code Playgroud)

但是,您根本不应该手动构造消息。Python在email.message中包括各种可爱的类,用于构造消息。

import email.message

m = email.message.Message()
m['From'] = "fromuser@host.com"
m['To'] = "touser@host.com"
m['Subject'] = "Send mail from python!!"

m.set_payload("Your text only body");
Run Code Online (Sandbox Code Playgroud)

现在,您可以将消息转换为字符串:

>>> m.as_string()
'To: touser@host.com\nFrom: fromuser@host.com\nSubject: Send mail from python!!\n\nyour text-only body'
Run Code Online (Sandbox Code Playgroud)

我会警告您,正确处理电子邮件是一个非常大而复杂的主题,如果您要使用非ascii,附件等内容,则会有一些学习上的困难,并且您将需要使用email.message库,其中包含许多您应该阅读和理解的文档。