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处理中文编码和判断编码示例
Feb 26 Python
python网络编程实例简析
Sep 26 Python
python实现RSA加密(解密)算法
Feb 17 Python
Python3实现发送QQ邮件功能(附件)
Dec 23 Python
Centos7 Python3下安装scrapy的详细步骤
Mar 15 Python
python调用Matplotlib绘制分布点并且添加标签
May 31 Python
python实现静态web服务器
Sep 03 Python
在win64上使用bypy进行百度网盘文件上传功能
Jan 02 Python
python判断链表是否有环的实例代码
Jan 31 Python
tensorflow对图像进行拼接的例子
Feb 05 Python
解决python中0x80072ee2错误的方法
Jul 19 Python
python 浮点数四舍五入需要注意的地方
Aug 18 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
source.php查看源文件
2006/12/09 PHP
XAMPP安装与使用方法详细解析
2013/11/27 PHP
Java中final关键字详解
2015/08/10 PHP
以实例全面讲解PHP中多进程编程的相关函数的使用
2015/08/18 PHP
php 在字符串指定位置插入新字符的简单实现
2016/06/28 PHP
tp5框架使用composer实现日志记录功能示例
2019/01/10 PHP
php学习笔记之字符串常见操作总结
2019/07/16 PHP
Laravel5.1 框架Request请求操作常见用法实例分析
2020/01/04 PHP
JavaScript中的闭包原理分析
2010/03/08 Javascript
jQuery中noconflict函数的实现原理分解
2015/02/03 Javascript
JS实现让网页背景图片斜向移动的方法
2015/02/25 Javascript
基于javascript如何传递特殊字符
2015/11/30 Javascript
jquery.serialize() 函数语法及简单实例
2016/07/08 Javascript
浅谈javascript中的Function和Arguments
2016/08/30 Javascript
jQuery时间验证和转换为标准格式的时间格式
2017/03/06 Javascript
jQuery日程管理控件glDatePicker用法详解
2017/03/29 jQuery
jquery 一键复制到剪切板的实例
2017/09/20 jQuery
详解React-Native全球化多语言切换工具库react-native-i18n
2017/11/03 Javascript
nodejs项目windows下开机自启动的方法
2017/11/22 NodeJs
详解node.js中的npm和webpack配置方法
2018/01/21 Javascript
Vue-cli项目获取本地json文件数据的实例
2018/03/07 Javascript
微信小程序实现canvas分享朋友圈海报
2020/06/21 Javascript
python创建线程示例
2014/05/06 Python
简单使用Python自动生成文章
2014/12/25 Python
Python实现一个简单的MySQL类
2015/01/07 Python
Python3.x版本中新的字符串格式化方法
2015/04/24 Python
Python 查看文件的编码格式方法
2017/12/21 Python
使用Python读取二进制文件的实例讲解
2018/07/09 Python
python实现五子棋游戏(pygame版)
2020/01/19 Python
Python编程快速上手——选择性拷贝操作案例分析
2020/02/28 Python
HTML5通过调用canvas对象的getContext()方法来获取绘图环境
2014/06/23 HTML / CSS
英国品牌男装折扣网站:Brown Bag
2018/03/08 全球购物
缓刑人员思想汇报
2014/10/11 职场文书
欠款证明
2015/06/24 职场文书
2015年幼儿园师德师风建设工作总结
2015/10/23 职场文书
Redis特殊数据类型Geospatial地理空间
2022/06/01 Redis