当前位置 : 主页 > 编程语言 > java >

python发送邮件sendmail--smtplib【带附件】

来源:互联网 收集:自由互联 发布时间:2023-02-04
#!/usr/bin/env python# -*- coding: UTF-8 -*-from email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBasefrom email.mime.text import MIMEText from email.utils import COMMASPACE,formatdatefrom email import encoders impor

#!/usr/bin/env python# -*- coding: UTF-8 -*-from email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBasefrom email.mime.text import MIMEText from email.utils import COMMASPACE,formatdatefrom email import encoders import os def send_mail(server, fro, to, subject, text, files=[]): assert type(server) == dict assert type(to) == list assert type(files) == list msg = MIMEMultipart() msg['From'] = fro msg['Subject'] = subject msg['To'] = COMMASPACE.join(to) #COMMASPACE==', ' msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data part.set_payload(open(f, 'rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) import smtplib smtp = smtplib.SMTP(server['name'], server['port']) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(server['user'], server['passwd']) smtp.sendmail(fro, to, msg.as_string()) smtp.close() if __name__=='__main__': server = {'name':'mail.server.com', 'user':'chenxiaowu', 'passwd':'xxxx', 'port':25} fro = 'chenxiaowu@163.com' to = ['xxxx@163.com'] subject = '脚本运行提醒' text = 'mail content' files = ['top_category.txt'] send_mail(server, fro, to, subject, text, files=files)

从网上找了些资料,不会有个别错误,上面代码经调试测试通过

上一篇:python抓网页资源小脚本
下一篇:没有了
网友评论