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 SQLite3数据库操作类分享
Jun 10 Python
python将文本转换成图片输出的方法
Apr 28 Python
Python argv用法详解
Jan 08 Python
Flask 让jsonify返回的json串支持中文显示的方法
Mar 26 Python
Python numpy 点数组去重的实例
Apr 18 Python
Python可变参数*args和**kwargs用法实例小结
Apr 27 Python
很酷的python表白工具 你喜欢我吗
Apr 11 Python
python 列表中[ ]中冒号‘:’的作用
Apr 30 Python
Django项目主urls导入应用中views的红线问题解决
Aug 10 Python
PyTorch中Tensor的拼接与拆分的实现
Aug 18 Python
使用Python三角函数公式计算三角形的夹角案例
Apr 15 Python
Python使用Selenium实现淘宝抢单的流程分析
Jun 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
elgg 获取文件图标地址的方法
2010/03/20 PHP
PHP生成唯一的促销/优惠/折扣码(附源码)
2012/12/28 PHP
PHP实现适用于自定义的验证码类
2016/06/15 PHP
jQuery使用手册之一
2007/03/24 Javascript
javascript 尚未实现错误解决办法
2008/11/27 Javascript
用JavaScript修改CSS属性的代码
2013/05/06 Javascript
JavaScript中textRange对象使用方法小结
2015/03/24 Javascript
bootstrap3 兼容IE8浏览器!
2016/05/02 Javascript
非常优秀的JS图片轮播插件Swiper的用法
2017/01/03 Javascript
微信小程序 支付功能(前端)的实现
2017/05/24 Javascript
Bootstrap Multiselect 常用组件实现代码
2017/07/09 Javascript
js字符串处理之绝妙的代码
2019/04/05 Javascript
Node.js API详解之 console模块用法详解
2020/05/12 Javascript
Python处理中文标点符号大集合
2018/05/14 Python
Python解决两个整数相除只得到整数部分的实例
2018/11/10 Python
Face++ API实现手势识别系统设计
2018/11/21 Python
详解Python3 对象组合zip()和回退方式*zip
2019/05/15 Python
在Python中画图(基于Jupyter notebook的魔法函数)
2019/10/28 Python
Python脚本导出为exe程序的方法
2020/03/25 Python
让Django的BooleanField支持字符串形式的输入方式
2020/05/20 Python
加拿大床上用品、家居装饰、厨房和浴室产品购物网站:Linen Chest
2018/06/05 全球购物
日本著名化妆品零售网站:Cosme Land
2019/03/01 全球购物
大学生自荐信
2013/12/11 职场文书
总经理岗位职责范本
2014/02/02 职场文书
安全生产月宣传标语
2014/10/06 职场文书
交通事故一次性赔偿协议书范本
2014/11/02 职场文书
2014年幼儿园教学工作总结
2014/12/04 职场文书
社区五一劳动节活动总结
2015/02/09 职场文书
写给女朋友的检讨书
2015/05/06 职场文书
常住证明范本
2015/06/23 职场文书
小学运动会加油稿
2015/07/22 职场文书
患者身份识别制度
2015/08/06 职场文书
Vue3 Composition API的使用简介
2021/03/29 Vue.js
Spring Boot mybatis-config 和 log4j 输出sql 日志的方式
2021/07/26 Java/Android
CSS作用域(样式分割)的使用汇总
2021/11/07 HTML / CSS
Nginx速查手册及常见问题
2022/04/07 Servers