简单实现python收发邮件功能

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

1. 准备工作

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

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

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

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的第二个元素中,其存储形式为一个数组。我们测试一下,该数组是怎么样的。

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

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

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邮箱。

测试结果如下:

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

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

(0)

相关推荐

  • python发送邮件的实例代码(支持html、图片、附件)

    第一段代码: 复制代码 代码如下: #!/usr/bin/python# -*- coding: utf-8 -*- import emailimport mimetypesfrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEText import MIMETextfrom email.MIMEImage import MIMEImageimport smtplib def sendEmail(authInfo, fromAdd

  • Python群发邮件实例代码

    直接上代码了 复制代码 代码如下: import smtplibmsg = MIMEMultipart() #构造附件1att1 = MIMEText(open('/home/a2bgeek/develop/python/hello.py', 'rb').read(), 'base64', 'gb2312')att1["Content-Type"] = 'application/octet-stream'att1["Content-Disposition"] = '

  • Python使用smtplib模块发送电子邮件的流程详解

    1.登录SMTP服务器 首先使用网上的方法(这里使用163邮箱,smtp.163.com是smtp服务器地址,25为端口号): import smtplib server = smtplib.SMTP('smtp.163.com', 25) server.login('j_hao104@163.com', 'password') Traceback (most recent call last): File "C:/python/t.py", line 192, in <modu

  • 在Python中使用poplib模块收取邮件的教程

    SMTP用于发送邮件,如果要收取邮件呢? 收取邮件就是编写一个MUA作为客户端,从MDA把邮件获取到用户的电脑或者手机上.收取邮件最常用的协议是POP协议,目前版本号是3,俗称POP3. Python内置一个poplib模块,实现了POP3协议,可以直接用来收邮件. 注意到POP3协议收取的不是一个已经可以阅读的邮件本身,而是邮件的原始文本,这和SMTP协议很像,SMTP发送的也是经过编码后的一大段文本. 要把POP3收取的文本变成可以阅读的邮件,还需要用email模块提供的各种类来解析原始文本

  • 详细讲解用Python发送SMTP邮件的教程

    SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件.HTML邮件以及带附件的邮件. Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件. 首先,我们来构造一个最简单的纯文本邮件: from email.mime.text import MIMEText msg = MIMEText('hello, send by Python...', 'plain', 'utf-8') 注意到构造MIMEText对象时

  • python 七种邮件内容发送方法实例

    一.文件形式的邮件 复制代码 代码如下: #!/usr/bin/env python3#coding: utf-8import smtplibfrom email.mime.text import MIMETextfrom email.header import Header sender = '***'receiver = '***'subject = 'python email test'smtpserver = 'smtp.163.com'username = '***'password

  • Python实现SMTP发送邮件详细教程

    简介 Python发送邮件的教程本人在网站搜索的时候搜索出来了一大堆,但是都是说了一大堆原理然后就推出了实现代码,我测试用给出的代码进行发送邮件时都不成功,后面找了很久才找到原因,这都是没有一个详细的环境调试导致,所以今天特出一个详细的教程,一步一步从环境调试到代码实现整一个教程,希望对还在苦苦寻找解决方法却迟迟不能得到有效解决的人员一点帮助. SMTP协议 首先了解SMTP(简单邮件传输协议),邮件传送代理程序使用SMTP协议来发送电邮到接收者的邮件服务器.SMTP协议只能用来发送邮件,不能用

  • python同时给两个收件人发送邮件的方法

    本文实例讲述了python同时给两个收件人发送邮件的方法.分享给大家供大家参考.具体分析如下: 该范例通过python内置的smtplib包发送邮件 import smtplib import string host = "localhost" fromclause = "a@b.com" toclause = "c@d.com, e@f.com" toclause = string.splitfields(toclause, ",&q

  • python中使用smtplib和email模块发送邮件实例

    SMTP模块 这么多已定义的类中,我们最常用的的还是smtplib.SMTP类,就具体看看该类的用法:smtp实例封装一个smtp连接,它支持所有的SMTP和ESMTP操作指令,如果host和port参数被定义,则smtp会在初始化期间自动调用connect()方法,如果connect()方法失败,则会触发SMTPConnectError异常,timeout参数设置了超时时间.在一般的调用过程中,应该遵connetc().sendmail().quit()步骤. SMTP模块主要方法 下面我们来

  • Python实现给qq邮箱发送邮件的方法

    本文实例讲述了Python实现给qq邮箱发送邮件的方法.分享给大家供大家参考.具体实现方法如下: #-*-coding:utf-8-*- #========================================== # 导入smtplib和MIMEText #========================================== from email.mime.text import MIMEText import smtplib #===================

随机推荐