简体   繁体   English

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

[英]python sending email with text and attachment

I wrote a script for backing up my Neo4J DB. 我写了一个脚本来备份我的Neo4J数据库。

At the end of the backup process and email is sent to the DB Administrator 在备份过程结束时,电子邮件将发送给数据库管理员

The email received without the message_body . 收到的电子邮件没有message_body

This is the code: 这是代码:

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)

Any idea why? 知道为什么吗?

MIMEMultipart takes as a parameter to the constructor a multipart subtype. MIMEMultipart将构造函数作为参数作为多部分子类型。

You were using the subtype 'alternative' . 您正在使用子类型'alternative' The alternative subtype allows the email to be sent with HTML and text. 替代子类型允许使用HTML和文本发送电子邮件。

You wanted to submit an email with text and an attachment, so you need to construct MIMEMultipart with the subtype 'mixed' . 您想要提交包含文本和附件的电子邮件,因此您需要使用子类型'mixed'构建MIMEMultipart

For more details about these subtypes, you can look at the MIME Wikipedia entry on Multipart messages . 有关这些子类型的更多详细信息,您可以查看有关Multipart消息的MIME Wikipedia条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM