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 相关文章推荐
Python的Flask框架中Flask-Admin库的简单入门指引
Apr 07 Python
Python利用正则表达式匹配并截取指定子串及去重的方法
Jul 30 Python
完美解决python遍历删除字典里值为空的元素报错问题
Sep 11 Python
python 开发的三种运行模式详细介绍
Jan 18 Python
Python内置模块ConfigParser实现配置读写功能的方法
Feb 12 Python
对numpy中数组元素的统一赋值实例
Apr 04 Python
Pycharm 文件更改目录后,执行路径未更新的解决方法
Jul 19 Python
Python datetime包函数简单介绍
Aug 28 Python
python  ceiling divide 除法向上取整(或小数向上取整)的实例
Dec 27 Python
python实现mean-shift聚类算法
Jun 10 Python
利用Python实现字幕挂载(把字幕文件与视频合并)思路详解
Oct 21 Python
教你使用一行Python代码玩遍童年的小游戏
Aug 23 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中对xml读取的相关函数的介绍一
2008/06/05 PHP
PHP下通过系统信号量加锁方式获取递增序列ID
2009/09/25 PHP
php 图片加水印与上传图片加水印php类
2010/05/12 PHP
PHP在线生成二维码代码(google api)
2013/06/03 PHP
php基于str_pad实现卡号不足位数自动补0的方法
2014/11/12 PHP
php实现四舍五入的方法小结
2015/03/03 PHP
详解 PHP加密解密字符串函数附源码下载
2015/12/18 PHP
js location.replace与location.reload的区别
2010/09/08 Javascript
常见效果实现之返回顶部(结合淡入、淡出、减速滚动)
2012/01/04 Javascript
javascript之typeof、instanceof操作符使用探讨
2013/05/19 Javascript
jQuery Mobile的loading对话框显示/隐藏方法分享
2013/11/26 Javascript
jquery ajax jsonp跨域调用实例代码
2013/12/11 Javascript
浅析js预加载/延迟加载
2014/09/25 Javascript
原生的html元素选择器类似jquery选择器
2014/10/15 Javascript
封装了jQuery的Ajax请求全局配置
2015/02/05 Javascript
jQuery插件slick实现响应式移动端幻灯片图片切换特效
2015/04/12 Javascript
一个仿微博登陆邮箱提示框js开发案例
2016/07/28 Javascript
Bootstrap栅格系统的使用和理解2
2016/12/14 Javascript
Ext JS 实现建议词模糊动态搜索功能
2017/05/13 Javascript
详解VUE中v-bind的基本用法
2017/07/13 Javascript
详解vuex的简单使用
2018/03/12 Javascript
详解nodejs解压版安装和配置(带有搭建前端项目脚手架)
2018/12/06 NodeJs
基于Bootstrap和JQuery实现动态打开和关闭tab页的实例代码
2019/06/10 jQuery
对TypeScript库进行单元测试的方法
2019/07/18 Javascript
Pyinstaller将py打包成exe的实例
2018/03/31 Python
python+selenium自动化实战携带cookies模拟登陆微博
2021/01/19 Python
茱莉蔻美国官网:Jurlique美国
2020/11/24 全球购物
中学生差生评语
2014/01/30 职场文书
法人授权委托书范本
2014/04/04 职场文书
领导班子四风问题个人对照检查材料
2014/10/04 职场文书
六查六看个人剖析材料
2014/10/14 职场文书
环卫个人总结
2015/03/03 职场文书
2015年社区矫正工作总结
2015/04/21 职场文书
保护环境建议书作文400字
2015/09/14 职场文书
Go语言-为什么返回值为接口类型,却返回结构体
2021/04/24 Golang
Python实战之大鱼吃小鱼游戏的实现
2022/04/01 Python