简单实现python收发邮件功能


Posted in Python onJanuary 05, 2018

今天记录一下如何使用python收发邮件,知识要点在python内置的poplib和stmplib模块的使用上。

1. 准备工作

首先,我们需要有一个测试邮箱,我们使用新浪邮箱,而且要进行如下设置:

简单实现python收发邮件功能

在新浪邮箱首页的右上角找到设置->更多设置,然后在左边选择“客户端/pop/imap/smtp”:

简单实现python收发邮件功能

最后,将Pop3/smtp服务的服务状态打开即可:

简单实现python收发邮件功能

2. poplib接收邮件

首先,介绍一下poplib登录邮箱和下载邮件的一些接口:

self.popHost = 'pop.sina.com' 
self.smtpHost = 'smtp.sina.com' 
self.port = 25 
self.userName = 'xxxxxx@sina.com' 
self.passWord = 'xxxxxx' 
self.bossMail = 'xxxxxx@qq.com'

我们需要如上一些常量,用于指定登录邮箱以及pop,smtp服务器及端口。我们调用poplib的POP3_SSL接口可以登录到邮箱。

# 登录邮箱 
def login(self): 
 try: 
  self.mailLink = poplib.POP3_SSL(self.popHost) 
  self.mailLink.set_debuglevel(0) 
  self.mailLink.user(self.userName) 
  self.mailLink.pass_(self.passWord) 
  self.mailLink.list() 
  print u'login success!' 
 except Exception as e: 
  print u'login fail! ' + str(e) 
  quit()

在登录邮箱的时候,很自然,我们需要提供用户名和密码,如上述代码所示,使用非常简单。
登录邮箱成功后,我们可以使用list方法获取邮箱的邮件信息。我们看到list方法的定义:

def list(self, which=None): 
 """Request listing, return result. 
 
 Result without a message number argument is in form 
 ['response', ['mesg_num octets', ...], octets]. 
 
 Result when a message number argument is given is a 
 single response: the "scan listing" for that message. 
 """ 
 if which is not None: 
  return self._shortcmd('LIST %s' % which) 
 return self._longcmd('LIST')

我们看到list方法的注释,其中文意思是,list方法有一个默认参数which,其默认值为None,当调用者没有给出参数时,该方法会列出所有邮件的信息,其返回形式为 [response, ['msg_number, octets', ...], octets],其中,response为响应结果,msg_number是邮件编号,octets为8位字节单位。我们看一看具体例子:
('+OK ', ['1 2424', '2 2422'], 16)
这是一个调用list()方法以后的返回结果。很明显,这是一个tuple,第一个值sahib响应结果'+OK',表示请求成功,第二个值为一个数组,存储了邮件的信息。例如'1 2424'中的1表示该邮件编号为1。
下面我们再看如何使用poplib下载邮件。

# 获取邮件 
def retrMail(self): 
 try: 
  mail_list = self.mailLink.list()[1] 
  if len(mail_list) == 0: 
   return None 
  mail_info = mail_list[0].split(' ') 
  number = mail_info[0] 
  mail = self.mailLink.retr(number)[1] 
  self.mailLink.dele(number) 
 
  subject = u'' 
  sender = u'' 
  for i in range(0, len(mail)): 
   if mail[i].startswith('Subject'): 
    subject = mail[i][9:] 
   if mail[i].startswith('X-Sender'): 
    sender = mail[i][10:] 
  content = {'subject': subject, 'sender': sender} 
  return content 
 except Exception as e: 
  print str(e) 
  return None

poplib获取邮件内容的接口是retr方法。其需要一个参数,该参数为要获取的邮件编号。下面是retr方法的定义:

def retr(self, which): 
 """Retrieve whole message number 'which'. 
 
 Result is in form ['response', ['line', ...], octets]. 
 """ 
 return self._longcmd('RETR %s' % which)

我们看到注释,可以知道,retr方法可以获取指定编号的邮件的全部内容,其返回形式为[response, ['line', ...], octets],可见,邮件的内容是存储在返回的tuple的第二个元素中,其存储形式为一个数组。我们测试一下,该数组是怎么样的。

简单实现python收发邮件功能

我们可以看到,这个数组的存储形式类似于一个dict!于是,我们可以据此找到任何我们感兴趣的内容。例如,我们的示例代码是要找到邮件的主题以及发送者,就可以按照上面的代码那样编写。当然,你也可以使用正则匹配~~~ 下面是测试结果:

简单实现python收发邮件功能

嗯...大家可以自己试一下。

3. smtp发送邮件

和pop一样,使用smtp之前也要先给它提供一些需要的常量:

self.mail_box = smtplib.SMTP(self.smtpHost, self.port) 
self.mail_box.login(self.userName, self.passWord)

上面是使用smtp登录邮箱的代码,和pop类似。下面给出使用smtp发送邮件的代码,你会看到python是多么的简单优美!

# 发送邮件 
def sendMsg(self, mail_body='Success!'): 
 try: 
  msg = MIMEText(mail_body, 'plain', 'utf-8') 
  msg['Subject'] = mail_body 
  msg['from'] = self.userName 
  self.mail_box.sendmail(self.userName, self.bossMail, msg.as_string()) 
  print u'send mail success!' 
 except Exception as e: 
  print u'send mail fail! ' + str(e)

这就是python用smtp发送邮件的代码!很简单有木有!很方便有木有!很通俗易懂有木有!这里主要就是sendmail这个方法,指定发送方,接收方和邮件内容就可以了。还有MIMEText可以看它的定义如下:

class MIMEText(MIMENonMultipart): 
 """Class for generating text/* type MIME documents.""" 
 
 def __init__(self, _text, _subtype='plain', _charset='us-ascii'): 
  """Create a text/* type MIME document. 
 
  _text is the string for this message object. 
 
  _subtype is the MIME sub content type, defaulting to "plain". 
 
  _charset is the character set parameter added to the Content-Type 
  header. This defaults to "us-ascii". Note that as a side-effect, the 
  Content-Transfer-Encoding header will also be set. 
  """ 
  MIMENonMultipart.__init__(self, 'text', _subtype, 
         **{'charset': _charset}) 
  self.set_payload(_text, _charset)

看注释~~~ 这就是一个生成指定内容,指定编码的MIME文档的方法而已。顺便看看sendmail方法吧~~~

def sendmail(self, from_addr, to_addrs, msg, mail_options=[], 
    rcpt_options=[]): 
 """This command performs an entire mail transaction. 
 
 The arguments are: 
  - from_addr : The address sending this mail. 
  - to_addrs  : A list of addresses to send this mail to. A bare 
       string will be treated as a list with 1 address. 
  - msg   : The message to send. 
  - mail_options : List of ESMTP options (such as 8bitmime) for the 
       mail command. 
  - rcpt_options : List of ESMTP options (such as DSN commands) for 
       all the rcpt commands.

嗯...使用smtp发送邮件的内容大概就这样了。

4. 源码及测试

# -*- coding:utf-8 -*- 
from email.mime.text import MIMEText 
import poplib 
import smtplib 
 
 
class MailManager(object): 
 
 def __init__(self): 
  self.popHost = 'pop.sina.com' 
  self.smtpHost = 'smtp.sina.com' 
  self.port = 25 
  self.userName = 'xxxxxx@sina.com' 
  self.passWord = 'xxxxxx' 
  self.bossMail = 'xxxxxx@qq.com' 
  self.login() 
  self.configMailBox() 
 
 # 登录邮箱 
 def login(self): 
  try: 
   self.mailLink = poplib.POP3_SSL(self.popHost) 
   self.mailLink.set_debuglevel(0) 
   self.mailLink.user(self.userName) 
   self.mailLink.pass_(self.passWord) 
   self.mailLink.list() 
   print u'login success!' 
  except Exception as e: 
   print u'login fail! ' + str(e) 
   quit() 
 
 # 获取邮件 
 def retrMail(self): 
  try: 
   mail_list = self.mailLink.list()[1] 
   if len(mail_list) == 0: 
    return None 
   mail_info = mail_list[0].split(' ') 
   number = mail_info[0] 
   mail = self.mailLink.retr(number)[1] 
   self.mailLink.dele(number) 
 
   subject = u'' 
   sender = u'' 
   for i in range(0, len(mail)): 
    if mail[i].startswith('Subject'): 
     subject = mail[i][9:] 
    if mail[i].startswith('X-Sender'): 
     sender = mail[i][10:] 
   content = {'subject': subject, 'sender': sender} 
   return content 
  except Exception as e: 
   print str(e) 
   return None 
 
 def configMailBox(self): 
  try: 
   self.mail_box = smtplib.SMTP(self.smtpHost, self.port) 
   self.mail_box.login(self.userName, self.passWord) 
   print u'config mailbox success!' 
  except Exception as e: 
   print u'config mailbox fail! ' + str(e) 
   quit() 
 
 # 发送邮件 
 def sendMsg(self, mail_body='Success!'): 
  try: 
   msg = MIMEText(mail_body, 'plain', 'utf-8') 
   msg['Subject'] = mail_body 
   msg['from'] = self.userName 
   self.mail_box.sendmail(self.userName, self.bossMail, msg.as_string()) 
   print u'send mail success!' 
  except Exception as e: 
   print u'send mail fail! ' + str(e) 
 
if __name__ == '__main__': 
 mailManager = MailManager() 
 mail = mailManager.retrMail() 
 if mail != None: 
  print mail 
  mailManager.sendMsg()

上述代码先登录邮箱,然后获取其第一封邮件并删除之,然后获取该邮件的主题和发送方并打印出来,最后再发送一封成功邮件给另一个bossMail邮箱。

测试结果如下:

简单实现python收发邮件功能

好的,大家可以把上面的代码复制一下,自己玩一下呗

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

Python 相关文章推荐
使用py2exe在Windows下将Python程序转为exe文件
Mar 04 Python
Swift中的协议(protocol)学习教程
Jul 08 Python
使用Python实现从各个子文件夹中复制指定文件的方法
Oct 25 Python
对python制作自己的数据集实例讲解
Dec 12 Python
python 判断linux进程,并杀死进程的实现方法
Jul 01 Python
Django中在xadmin中集成DjangoUeditor过程详解
Jul 24 Python
Django框架视图层URL映射与反向解析实例分析
Jul 29 Python
Python list与NumPy array 区分详解
Nov 06 Python
春节到了 教你使用python来抢票回家
Jan 06 Python
解决pytorch多GPU训练保存的模型,在单GPU环境下加载出错问题
Jun 23 Python
Python pip安装第三方库实现过程解析
Jul 09 Python
Pygame如何使用精灵和碰撞检测
Nov 17 Python
5款非常棒的Python工具
Jan 05 #Python
Python基于列表模拟堆栈和队列功能示例
Jan 05 #Python
Django 2.0版本的新特性抢先看!
Jan 05 #Python
微信跳一跳游戏python脚本
Apr 01 #Python
Python基于列表list实现的CRUD操作功能示例
Jan 05 #Python
django 2.0更新的10条注意事项总结
Jan 05 #Python
OpenCV2.3.1+Python2.7.3+Numpy等的配置解析
Jan 05 #Python
You might like
PHP中查询SQL Server或Sybase时TEXT字段被截断的解决方法
2009/03/10 PHP
PHP has encountered a Stack overflow问题解决方法
2014/11/03 PHP
PHP读书笔记_运算符详解
2016/07/01 PHP
PHP学习记录之常用的魔术常量详解
2019/12/12 PHP
javascript+dom树型菜单类,希望朋友们一起进步
2007/05/03 Javascript
分享一个用Mootools写的鼠标滑过进度条改变进度值的实现代码
2011/12/12 Javascript
JS返回上一页实例代码通过图片和按钮分别实现
2013/08/16 Javascript
Bootstrap零基础入门教程(二)
2016/07/18 Javascript
用js实现博客打赏功能
2016/10/24 Javascript
jQuery Ajax File Upload实例源码
2016/12/12 Javascript
Node.js使用gm拼装sprite图片
2017/07/04 Javascript
谈谈对vue响应式数据更新的误解
2017/08/01 Javascript
基于jQuery选择器之表单对象属性筛选选择器的实例
2017/09/19 jQuery
使用JavaScript实现一个小程序之99乘法表
2017/09/21 Javascript
React Native 使用Fetch发送网络请求的示例代码
2017/12/02 Javascript
解决vue打包项目后刷新404的问题
2018/03/06 Javascript
在vue-cli中引入lodash.js并使用详解
2019/11/13 Javascript
在 Vue 中使用 JSX 及使用它的原因浅析
2020/02/10 Javascript
JQuery基于FormData异步提交数据文件
2020/09/01 jQuery
Nuxt的动态路由和参数校验操作
2020/11/09 Javascript
[01:24:16]2018DOTA2亚洲邀请赛 4.6 全明星赛
2018/04/10 DOTA
Python抓取框架 Scrapy的架构
2016/08/12 Python
Python中函数及默认参数的定义与调用操作实例分析
2017/07/25 Python
Python分治法定义与应用实例详解
2017/07/28 Python
python通过Windows下远程控制Linux系统
2018/06/20 Python
Python MySQL 日期时间格式化作为参数的操作
2020/03/02 Python
python中selenium库的基本使用详解
2020/07/31 Python
Python识别处理照片中的条形码
2020/11/16 Python
分享8款纯CSS3实现的搜索框功能
2017/09/14 HTML / CSS
90后毕业生的求职信范文
2013/09/21 职场文书
人力资源部培训专员岗位职责
2014/01/02 职场文书
校园广播稿100字
2014/10/06 职场文书
2014企业年终工作总结
2014/12/23 职场文书
2015大学生暑期实习报告
2015/07/13 职场文书
学习《中小学教师职业道德规范》心得体会
2016/01/18 职场文书
Java各种比较对象的方式的对比总结
2021/06/20 Java/Android