当前位置:  编程技术>python

python发送邮件接收邮件示例分享

    来源: 互联网  发布时间:2014-09-04

    本文导语:  接收邮件 代码如下:import poplib,pdb,email,re,timefrom email import header POP_ADDR = r'pop.126.com'USER = ''PASS = ''CONFIG = '' def getYear(date):    rslt = re.search(r'b2d{3}b', date)    return int(rslt.group()) def getMonth(date):    monthMap = {'Jan':1,'Feb':2,'Mar':3,'Apr':...

接收邮件

代码如下:

import poplib,pdb,email,re,time
from email import header

POP_ADDR = r'pop.126.com'
USER = ''
PASS = ''
CONFIG = ''

def getYear(date):
    rslt = re.search(r'b2d{3}b', date)
    return int(rslt.group())

def getMonth(date):
    monthMap = {'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,
                'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12,}

    rslt = re.findall(r'bw{3}b', date)
    for i in range(len(rslt)):
        month = monthMap.get(rslt[i])
        if None != month:
            break

    return month

def getDay(date):
    rslt = re.search(r'bd{1,2}b', date)
    return int(rslt.group())

def getTime(date):
    rslt = re.search(r'bd{2}:d{2}:d{2}b', date)
    timeList = rslt.group().split(':')

    for i in range(len(timeList)):
        timeList[i] = int(timeList[i])

    return timeList

def transformDate(date):
    rslt = getYear(date)
    rslt = rslt * 100
    rslt = rslt + getMonth(date)
    rslt = rslt * 100
    rslt = rslt + getDay(date)
      

    timeList = getTime(date)
    for i in range(len(timeList)):
        rslt = rslt * 100
        rslt = rslt + timeList[i]

    print(rslt)
    return rslt

def getRecentReadMailTime():
    fp = open(CONFIG, 'r')
    rrTime = fp.read()
    fp.close()
    return rrTime

def setRecentReadMailTime():
    fp = open(CONFIG, 'w')
    fp.write(time.ctime())
    fp.close()
    return

def parseMailSubject(msg):
    subSrt = msg.get('subject')
    if None == subSrt:
        subject = '无主题'
    else:
        subList = header.decode_header(subSrt)
        subinfo = subList[0][0]
        subcode = subList[0][1]

        if isinstance(subinfo,bytes):
            subject = subinfo.decode(subcode)
        else:
            subject = subinfo

    print(subject)

def parseMailContent(msg):
    if msg.is_multipart():
        for part in msg.get_payload():
            parseMailContent(part)
    else:
        bMsgStr = msg.get_payload(decode=True)
        charset = msg.get_param('charset')
        msgStr = 'Decode Failed'
        try:
            if None == charset:
                msgStr = bMsgStr.decode()
            else:
                msgStr = bMsgStr.decode(charset)
        except:
            pass

        print(msgStr)

def recvEmail():
    server = poplib.POP3(POP_ADDR)
    server.user(USER)
    server.pass_(PASS)

    mailCount,size = server.stat()
    mailNoList = list(range(mailCount))
    mailNoList.reverse()

    hisTime = transformDate(getRecentReadMailTime())
    setRecentReadMailTime()
    #pdb.set_trace()
    for i in mailNoList:
        message = server.retr(i+1)[1]
        mail = email.message_from_bytes(b'n'.join(message))

        if transformDate(mail.get('Date')) > hisTime:
            parseMailSubject(mail)
            #parseMailContent(mail)
        else:
            break

recvEmail()

发送邮件:

代码如下:

import os,pdb,smtplib,time,mimetypes
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage

COMMASPACE = ','
SONG_PATH = r''
RECORD_FILE = ''
PIC_PATH  = ''
CC = []
TO = []
ME = ''
SMTP_SERVER = 'smtp.126.com'
USER = ''
PASS = ''

def constructAddr(addrList):
    return COMMASPACE.join(addrList)

def willChooseThisMedia(media, path):
    fp = open(path + RECORD_FILE, 'r')
    shareInfo = fp.read()
    fp.close()

    shareInfoList = shareInfo.split('n')

    if media not in shareInfoList:
        fp = open(path + RECORD_FILE, 'a')
        fp.write(media + 'n')
        fp.close()
        return True
    else:
        return False

def getTodayMedia(path):
    mediaList = os.listdir(path)

    for media in mediaList:
        if False == os.path.isfile(path + media):
            continue
        else:
            if (media.endswith('mp3') or media.lower().endswith('jpg')) and
                willChooseThisMedia(media, path):
                return media

def getMIMEImage(pic): 
    fp = open(PIC_PATH + pic, 'rb')
    imageType = mimetypes.guess_type(PIC_PATH + pic)
    image = MIMEImage(fp.read(),imageType[0].split('/')[1])
    fp.close()
    image.add_header('Content-Disposition', 'attachment')
    image.set_param('filename', pic, header = 'Content-Disposition', charset = 'gb2312')

    return image

def getMIMEAudio(song): 
    fp = open(SONG_PATH + song, 'rb')
    audioType = mimetypes.guess_type(SONG_PATH + song)
    audio = MIMEAudio(fp.read(),audioType[0].split('/')[1])
    fp.close()
    audio.add_header('Content-Disposition', 'attachment')
    audio.set_param('filename', song, header = 'Content-Disposition', charset = 'gb2312')

    return audio

def constructMail():
    mail = MIMEMultipart()

    song = getTodayMedia(SONG_PATH)
    pic  = getTodayMedia(PIC_PATH)

    mailSubject = Header('今日分享 | ' + song, 'utf-8')
    mailDate = Header(time.ctime())

    mail['subject'] = mailSubject
    mail['date'] = mailDate
    mail['to'] = constructAddr(TO)
    mail['cc'] = constructAddr(CC)
    mail['from'] = ME

    mailBody = MIMEText(song, _charset='gb2312')
    mail.attach(mailBody)
    mail.attach(getMIMEAudio(song))
    mail.attach(getMIMEImage(pic))
    return mail

def sendMail():
    session = smtplib.SMTP(SMTP_SERVER)
    session.login(USER,PASS)
    mail = constructMail()
    session.sendmail(ME, constructAddr(TO), mail.as_string())
    session.quit()

sendMail()


    
 
 

您可能感兴趣的文章:

  • 二种python发送邮件实例讲解(python发邮件附件可以使用email模块实现)
  • Python群发邮件实例代码
  • python发送邮件示例(支持中文邮件标题)
  • 用smtplib和email封装python发送邮件模块类分享
  • python 七种邮件内容发送方法实例
  • python中使用smtplib和email模块发送邮件实例
  • python发送邮件的实例代码(支持html、图片、附件)
  • Python获取网页编码的方法及示例代码
  • python读取csv文件示例(python操作csv)
  • python下xml解析库lxml最新版下载安装以及代码示例
  • python基础教程之python消息摘要算法使用示例
  • 数据结构:图(有向图,无向图),在Python中的表示和实现代码示例
  • python实现绘制树枝简单示例
  • 使用python删除nginx缓存文件示例(python文件操作)
  • python学习手册中的python多态示例代码
  • python调用windows api锁定计算机示例
  • python代码制作configure文件示例
  • python使用循环实现批量创建文件夹示例
  • python采用requests库模拟登录和抓取数据的简单示例
  • Python数组条件过滤filter函数使用示例
  • python获得图片base64编码示例
  • Python的print用法示例
  • python文件读写并使用mysql批量插入示例分享(python操作mysql)
  • Python pass 语句使用示例
  • python getopt 参数处理小示例
  • python的urllib模块显示下载进度示例
  • python list转dict示例分享
  • python求素数示例分享
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • shell脚本中执行python脚本并接收其返回值的例子
  • 使用PYTHON接收多播数据的代码
  • Python GUI编程:tkinter实现一个窗口并居中代码
  • 让python同时兼容python2和python3的8个技巧分享
  • Python不使用print而直接输出二进制字符串
  • 使用setup.py安装python包和卸载python包的方法
  • Python中实现json字符串和dict类型的互转
  • 不小心把linux自带的python卸载了,导致安装一个依赖原python的软件不能安装,请问该怎么办?
  • python异常信息堆栈输出到日志文件
  • Python开发者社区整站源码 Pythoner
  • python下用os.execl执行centos下的系统时间同步命令ntpdate
  • 新手该如何学python怎么学好python?
  • Python namedtuple对象json序列化/反序列化及对象恢复
  • 请教:system("C:\python2.4\python.exe C:\aa.py");该语句有何错误?为什么运行界面一闪就消失了并且没有运行完,请给出正确语句!
  • Python异常模块traceback用法举例
  • python版本的问题
  • python之平台独立的调试工具winpdb介绍
  • Mac OS X10.9安装的Python2.7升级Python3.3步骤详解
  • 基于Python的Html/xml解析库Beautiful Soup 4.2.1发布
  • python安装的问题
  • 测试Python内部类型及type和isinstance用法区别
  • 如何运行Python程序的方法
  • Python3中内置类型bytes和str用法及byte和string之间各种编码转换
  • 明明安装了python却提示找不到!!


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3