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

yipeiwu_com5年前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设计】。

相关文章

Python3中的最大整数和最大浮点数实例

Python中的最大整数 Python中可以通过sys模块来得到int的最大值. python2中使用的方法是 import sys max = sys.maxint print (...

解析Python中的__getitem__专有方法

__getitem__ 来看个简单的例子就明白: def __getitem__(self, key): return self.data[key] >>> f...

Python subprocess模块详细解读

Python subprocess模块详细解读

本文研究的主要是Python subprocess模块的相关内容,具体如下。 在学习这个模块前,我们先用Python的help()函数查看一下subprocess模块是干嘛的: DES...

图文讲解选择排序算法的原理及在Python中的实现

图文讲解选择排序算法的原理及在Python中的实现

基本思想:从未排序的序列中找到一个最小的元素,放到第一位,再从剩余未排序的序列中找到最小的元素,放到第二位,依此类推,直到所有元素都已排序完毕。假设序列元素总共n+1个,则我们需要找n轮...

Python在Console下显示文本进度条的方法

进度条实现原理 进度条和一般的print区别在哪里呢? 答案就是print会输出一个\n,也就是换行符,这样光标移动到了下一行行首,接着输出,之前已经通过stdout输出的东西依旧保留,...