Chr*_*ong 5 python smtplib python-2.7
以下Python函数导致附件在名称为"noname"时应为"text_file.txt".正如您所看到的,我尝试了两种不同的MIMEBase和MIMEApplication方法.我也试过MIMEMultipart('替代')无济于事.
def send_email(from_addr, to_addr_list,
subject, html_body,plain_text_body,
login,
password,
smtpserver='smtp.gmail.com:587',
cc_addr_list=None,
attachment=None,
from_name=None):
message=MIMEMultipart()
plain=MIMEText(plain_text_body,'plain')
html=MIMEText(html_body,'html')
message.add_header('from',from_name)
message.add_header('to',','.join(to_addr_list))
message.add_header('subject',subject)
if attachment!=None:
#attach_file=MIMEBase('application',"octet-stream")
#attach_file.set_payload(open(attachment,"rb").read())
#Encoders.encode_base64(attach_file)
#f.close()
attach_file=MIMEApplication(open(attachment,"rb").read())
message.add_header('Content-Disposition','attachment; filename="%s"' % attachment)
message.attach(attach_file)
message.attach(plain)
message.attach(html)
server = smtplib.SMTP(smtpserver)
server.starttls()
server.login(login,password)
server.sendmail(from_addr, to_addr_list, message.as_string())
server.quit()
Run Code Online (Sandbox Code Playgroud)
我是如何调用函数的:
send_email(
from_addr=from_email,
to_addr_list=["some_address@gmail.com"],
subject=subject,
html_body=html,
plain_text_body=plain,
login=login,
password=password,
from_name=display_name,
attachment="text_file.txt"
)
Run Code Online (Sandbox Code Playgroud)
你的标题不正确.filename
属性不是字符串.
# Add header to variable with attachment file
attach_file.add_header('Content-Disposition', 'attachment', filename=attachment)
# Then attach to message attachment file
message.attach(attach_file)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3970 次 |
最近记录: |