我正在尝试使用带有附件的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()
电子邮件发送,邮箱收到它并查看附件 - 但是当试图打开它时,它说它无法打开文件。
答案 0 :(得分:2)
您忘记在open
中添加文件名。
filename = "nice.png"
attachment = open("C:\\Users\\Ben Hannah\\Documents", "rb")
尝试,
attachment = open("C:\\Users\\Ben Hannah\\Documents\\" + filename, "rb")