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

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

相关文章

Python中AND、OR的一个使用小技巧

python中的and-or可以用来当作c用的?:用法。比如 1 and a or b,但是需要确保a为True,否则a为False,还要继续判断b的值,最后打印b的值。 今天看到一个好...

老生常谈python的私有公有属性(必看篇)

python中,类内方法外的变量叫属性,类内方法内的变量叫字段。他们的私有公有访问方法类似。 class C: __name="私有属性" def func(self):...

在Python的gevent框架下执行异步的Solr查询的教程

 我经常需要用Python与solr进行异步请求工作。这里有段代码阻塞在Solr http请求上, 直到第一个完成才会执行第二个请求,代码如下:   impor...

YUV转为jpg图像的实现

调用opencv库,将yuv图像转为jpg图像。 代码如下: # define _CRT_SECURE_NO_WARNINGS #include <string> #in...

Python yield 小结和实例

一个带有 yield 的函数就是一个 generator,它和普通函数不同,生成一个 generator 看起来像函数调用,但不会执行任何函数代码,直到对其调用 next()(在 for...