Python 3.6 - 从Python发送电子邮件

时间:2017-09-26 13:21:45

标签: python email

我正在尝试使用带有附件的python发送电子邮件。这是我的代码:

ansible-playbook playbooks/environment-provisioning.yml -e env=perf -e
num_injectors_zone_a=2 -t performance_services -e
'aws_instance_tags={copa:copa2}'

这就是它回馈的内容:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

fromaddr = "name@company.com"
toaddr = "name2@company.com"

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Testing Python Email - Plus Attachments"

body = "This is an automated email"

msg.attach(MIMEText(body, 'plain'))

filename = "nice.png"
attachment = open("C:\\Users\\Ben Hannah\\Documents", "rb")

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.office365.com', 587)
server.starttls()
server.login(fromaddr, "************")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

电子邮件发送,邮箱收到它并查看附件 - 但是当试图打开它时,它说它无法打开文件。

1 个答案:

答案 0 :(得分:2)

您忘记在open中添加文件名。

filename = "nice.png"
attachment = open("C:\\Users\\Ben Hannah\\Documents", "rb")

尝试,

attachment = open("C:\\Users\\Ben Hannah\\Documents\\" + filename, "rb")