Python smtplib实现发送邮件功能


Posted in Python onMay 22, 2018

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

解决之前版本的问题,下面为最新版

#!/usr/bin/env python 
# coding:gbk 
 
""" 
FuncName: sendemail.py 
Desc: sendemail with text,image,audio,application... 
Date: 2016-06-20 10:30 
Home: http://blog.csdn.net/z_johnny 
Author: johnny 
""" 
 
from email.mime.multipart import MIMEMultipart 
from email.mime.application import MIMEApplication 
from email.utils import COMMASPACE 
from email.mime.text import MIMEText 
from email.mime.image import MIMEImage 
from email.mime.audio import MIMEAudio 
import ConfigParser 
import smtplib 
import os 
 
class MyEmail: 
 def __init__(self, email_config_path, email_attachment_path): 
  """ 
  init config 
  """ 
  config = ConfigParser.ConfigParser() 
  config.read(email_config_path) 
  self.attachment_path = email_attachment_path 
 
  self.smtp = smtplib.SMTP() 
  self.login_username = config.get('SMTP', 'login_username') 
  self.login_password = config.get('SMTP', 'login_password') 
  self.sender = config.get('SMTP', 'login_username') # same as login_username 
  self.receiver = config.get('SMTP', 'receiver') 
  self.host = config.get('SMTP', 'host') 
  #self.port = config.get('SMTP', 'port')  发现加入端口后有时候发邮件出现延迟,故暂时取消 
 
 def connect(self): 
  """ 
  connect server 
  """ 
  #self.smtp.connect(self.host, self.port) 
  self.smtp.connect(self.host) 
 
 def login(self): 
  """ 
  login email 
  """ 
  try: 
   self.smtp.login(self.login_username, self.login_password) 
  except: 
   raise AttributeError('Can not login smtp!!!') 
 
 def send(self, email_title, email_content): 
  """ 
  send email 
  """ 
  msg = MIMEMultipart()     # create MIMEMultipart 
  msg['From'] = self.sender    # sender 
  receiver = self.receiver.split(",")  # split receiver to send more user 
  msg['To'] = COMMASPACE.join(receiver) 
  msg['Subject'] = email_title   # email Subject 
  content = MIMEText(email_content, _charset='gbk') # add email content ,coding is gbk, becasue chinese exist 
  msg.attach(content) 
 
  for attachment_name in os.listdir(self.attachment_path): 
   attachment_file = os.path.join(self.attachment_path,attachment_name) 
 
   with open(attachment_file, 'rb') as attachment: 
    if 'application' == 'text': 
     attachment = MIMEText(attachment.read(), _subtype='octet-stream', _charset='GB2312') 
    elif 'application' == 'image': 
     attachment = MIMEImage(attachment.read(), _subtype='octet-stream') 
    elif 'application' == 'audio': 
     attachment = MIMEAudio(attachment.read(), _subtype='octet-stream') 
    else: 
     attachment = MIMEApplication(attachment.read(), _subtype='octet-stream') 
 
   attachment.add_header('Content-Disposition', 'attachment', filename = ('gbk', '', attachment_name)) 
   # make sure "attachment_name is chinese" right 
   msg.attach(attachment) 
 
  self.smtp.sendmail(self.sender, receiver, msg.as_string()) # format msg.as_string() 
 
 def quit(self): 
  self.smtp.quit() 
 
def send(): 
 import time 
 ISOTIMEFORMAT='_%Y-%m-%d_%A' 
 current_time =str(time.strftime(ISOTIMEFORMAT)) 
 
 email_config_path = './config/emailConfig.ini' # config path 
 email_attachment_path = './result'    # attachment path 
 email_tiltle = 'johnny test'+'%s'%current_time # as johnny test_2016-06-20_Monday ,it can choose only file when add time 
 email_content = 'python发送邮件测试,包含附件' 
 
 myemail = MyEmail(email_config_path,email_attachment_path) 
 myemail.connect() 
 myemail.login() 
 myemail.send(email_tiltle, email_content) 
 myemail.quit() 
 
if __name__ == "__main__": 
 # from sendemail import SendEmail 
 send()

配置文件emailConfig.ini

路径要与程序对应

;login_username : 登陆发件人用户名 
;login_password : 登陆发件人密码 
;host:port : 发件人邮箱对应的host和端口,如:smtp.163.com:25 和 smtp.qq.com:465 
;receiver : 收件人,支持多方发送,格式(注意英文逗号): 123456789@163.com,zxcvbnm@qq.com 

[SMTP] 
login_username = johnny@163.com 
login_password = johnny 
host = smtp.163.com 
port = 25 
receiver = johnny1@qq.com,johnny2@163.com,johnny3@gmail.com

之前版本出现的问题:

#!/usr/bin/env python 
#coding: utf-8 
 
''''' 
FuncName: smtplib_email.py 
Desc: 使用smtplib发送邮件 
Date: 2016-04-11 14:00 
Author: johnny 
''' 
 
import smtplib 
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 
from email.mime.base import MIMEBase 
from email.utils import COMMASPACE,formatdate 
from email import encoders 
 
def send_email_text(sender,receiver,host,subject,text,filename): 
  
 assert type(receiver) == list 
 
 msg = MIMEMultipart() 
 msg['From'] = sender 
 msg['To'] = COMMASPACE.join(receiver) 
 msg['Subject'] = subject 
 msg['Date'] = formatdate(localtime=True) 
 msg.attach(MIMEText(text))     #邮件正文内容 
 
 for file in filename:      #邮件附件 
  att = MIMEBase('application', 'octet-stream') 
  att.set_payload(open(file, 'rb').read()) 
  encoders.encode_base64(att) 
  if file.endswith('.html'):    # 若不加限定,jpg、html等格式附件是bin格式的 
   att.add_header('Content-Disposition', 'attachment; filename="今日测试结果.html"')   # 强制命名,名称未成功格式化,如果可以解决请联系我 
  elif file.endswith('.jpg') or file.endswith('.png') : 
   att.add_header('Content-Disposition', 'attachment; filename="pic.jpg"') 
  else: 
   att.add_header('Content-Disposition', 'attachment; filename="%s"' % file) 
  msg.attach(att) 
 
 smtp = smtplib.SMTP(host)   
 smtp.ehlo() 
 smtp.starttls() 
 smtp.ehlo() 
 smtp.login(username,password) 
 smtp.sendmail(sender,receiver, msg.as_string()) 
 smtp.close() 
 
if __name__=="__main__": 
 sender = 'qqq@163.com' 
 receiver = ['www@qq.com'] 
 subject = "测试" 
 text = "johnny'lab test" 
 filename = [u'测试报告.html','123.txt',u'获取的信息.jpg'] 
 host = 'smtp.163.com' 
 username = 'qqq@163.com' 
 password = 'qqq' 
 send_email_text(sender,receiver,host,subject,text,filename)

已测试通过,使用Header并没有变成“头”,故未使用

若能解决附件格式为(html、jpg、png)在邮箱附件中格式不为“bin”的请联系我,希望此对大家有所帮助,谢谢(已解决,见上面最新版

点击查看:Python 邮件smtplib发送示例 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python3实现并发检验代理池地址的方法
Sep 18 Python
Python读取和处理文件后缀为.sqlite的数据文件(实例讲解)
Jun 27 Python
Tensorflow实现AlexNet卷积神经网络及运算时间评测
May 24 Python
通过python顺序修改文件名字的方法
Jul 11 Python
Python对CSV、Excel、txt、dat文件的处理
Sep 18 Python
Python3实现爬虫爬取赶集网列表功能【基于request和BeautifulSoup模块】
Dec 05 Python
python利用跳板机ssh远程连接redis的方法
Feb 19 Python
Django模型序列化返回自然主键值示例代码
Jun 12 Python
Python上下文管理器类和上下文管理器装饰器contextmanager用法实例分析
Nov 07 Python
keras获得model中某一层的某一个Tensor的输出维度教程
Jan 24 Python
Python基于当前时间批量创建文件
May 07 Python
Python使用内置函数setattr设置对象的属性值
Oct 16 Python
linux下python使用sendmail发送邮件
May 22 #Python
Python实现的文本对比报告生成工具示例
May 22 #Python
python smtplib模块实现发送邮件带附件sendmail
May 22 #Python
点球小游戏python脚本
May 22 #Python
python smtplib模块自动收发邮件功能(二)
May 22 #Python
python smtplib模块自动收发邮件功能(一)
May 22 #Python
python模块smtplib学习
May 22 #Python
You might like
php 中的4种标记风格介绍
2012/05/10 PHP
PHP上传文件时文件过大$_FILES为空的解决方法
2013/11/26 PHP
php实现无限级分类
2014/12/24 PHP
PHP 绘制网站登录首页图片验证码
2016/04/12 PHP
PHP Post获取不到非表单数据的问题解决办法
2018/02/27 PHP
详解PHP实现支付宝小程序用户授权的工具类
2018/12/25 PHP
JavaScript中使用正则匹配多条,且获取每条中的分组数据
2010/11/30 Javascript
通过JS获取用户本地图片路径并显示的代码
2012/02/16 Javascript
javascript使用for循环批量注册的事件不能正确获取索引值的解决方法
2014/12/20 Javascript
node.js中axios使用心得总结
2017/11/29 Javascript
微信小程序生成分享海报方法(附带二维码生成)
2019/03/29 Javascript
Vue使用Proxy监听所有接口状态的方法实现
2019/06/07 Javascript
8个有意思的JavaScript面试题
2019/07/30 Javascript
python编程-将Python程序转化为可执行程序[整理]
2007/04/09 Python
Python简单的制作图片验证码实例
2017/05/31 Python
详谈python3中用for循环删除列表中元素的坑
2018/04/19 Python
Python针对给定字符串求解所有子序列是否为回文序列的方法
2018/04/21 Python
python读取csv文件并把文件放入一个list中的实例讲解
2018/04/27 Python
解决每次打开pycharm直接进入项目的问题
2018/10/28 Python
Python获取浏览器窗口句柄过程解析
2020/07/25 Python
python对输出的奇数偶数排序实例代码
2020/12/04 Python
美国高端婴童品牌:Hanna Andersson
2016/10/30 全球购物
英国殿堂级有机护肤品牌:Rodial
2017/04/17 全球购物
英国二手物品交易网站:Preloved
2017/10/06 全球购物
FLIR美国官网:热成像, 夜视和红外摄像系统
2018/07/13 全球购物
EJB面试题
2015/07/28 面试题
京剧自荐信
2014/01/26 职场文书
现金出纳岗位职责
2014/03/15 职场文书
工商行政管理专业求职书
2014/05/23 职场文书
商铺门前三包责任书
2014/07/25 职场文书
2016年会开场白台词
2015/06/01 职场文书
老兵退伍感言
2015/08/03 职场文书
患者身份识别制度
2015/08/06 职场文书
JavaScript实现班级抽签小程序
2021/05/19 Javascript
微信小程序基础教程之echart的使用
2021/06/01 Javascript
Windows Server 2019 安装DHCP服务及相关配置
2022/04/28 Servers