python发送带有文本和附件的电子邮件

时间:2016-01-10 15:06:23

标签: python smtp

我写了一个用于备份Neo4J DB的脚本。

在备份过程结束时,电子邮件将发送给数据库管理员

收到的电子邮件没有message_body

这是代码:

message = MIMEMultipart('alternative')
message['To'] = "Database Admin <%s>" % _receiver
message['From'] = "Pico.buzz Graph Database <%s>" % _sender
if not log.is_error():
    message['Subject'] = "Graph DB Backup Finished Successfully"
    message_body = 'Successfully backup email. Please see review log file'
else:
    message['Subject'] = "ATTENTION: ERROR! Graph DB Backup Failed"
    message_body = 'An error occur during backup. please review log'
instance_name = aws.get_instance_name()
instance_details = "Instance Id: %s\nPrivate IP Address: %s" % (aws.get_instance_id(), aws.get_instance_ip())
if instance_name is not None:
    instance_details = """Instance Name: %s\n%s""" % (instance_name, instance_details)
message_body = "%s\n\n%s" % (message_body, instance_details)
content = MIMEText(message_body, 'plain')
message.attach(content)
message.attach(_get_log_file())
smtp = smtplib.SMTP('localhost')
smtp.sendmail(_sender, _receiver, message.as_string())
log.info(__name__, "Successfully sent email to: %s" % _receiver)

知道为什么吗?

1 个答案:

答案 0 :(得分:0)

MIMEMultipart将构造函数作为参数作为多部分子类型。

您使用的是子类型'alternative'。替代子类型允许使用HTML和文本发送电子邮件。

您想提交包含文字和附件的电子邮件,因此您需要使用子类型MIMEMultipart构建'mixed'

有关这些子类型的更多详细信息,您可以查看Multipart messages上的MIME Wikipedia条目。