欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python smtplib模块实现发送邮件带附件sendmail

时间:2021-06-27 08:20:33|栏目:Python代码|点击:

本文实例为大家分享了python smtplib实现发送邮件的具体代码,供大家参考,具体内容如下

#!/usr/bin/env python 
# -*- coding: UTF-8 -*- 
 
from email.mime.multipart import MIMEMultipart 
from email.mime.base import MIMEBase 
from email.mime.text import MIMEText 
  
from email.utils import COMMASPACE,formatdate 
from 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安装mysql的依赖包mysql-python操作

栏    目:Python代码

下一篇:python sys,os,time模块的使用(包括时间格式的各种转换)

本文标题:python smtplib模块实现发送邮件带附件sendmail

本文地址:http://www.codeinn.net/misctech/148667.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有