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

时间:2014-02-07 22:58:13

标签: 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!"

这里的数据只有键值对。

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

在我的展望的From:部分中,下面的字符串即将出现,这是错误的 -

fromuser@host.com To: touser@host.com Subject: Send mail from python!!

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

在身体中,我看到一切都在一行,但我希望结果显示为 -

Some Text

machinA - 0
machineB - 0
machineC - 0

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

1 个答案:

答案 0 :(得分:5)

由于三重引用会保留所有空格,因此您无意中发送了:

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

这会调用标题展开:缩进行表示标题继续。所以这真的是一个格式错误的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!"

但是,您根本不应该手动构建消息。 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");

现在,您可以将邮件转换为字符串:

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

我会警告你,妥善处理电子邮件是一个非常庞大而复杂的话题,如果你想使用非ascii,附件等,那就有一点学习曲线,你需要使用所有的email.message库的功能,它有很多你应该阅读和理解的文档。

相关问题