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


Posted in Python onJanuary 21, 2014

接收邮件

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'\b2\d{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'\b\w{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'\b\d{1,2}\b', date)
    return int(rslt.group())
def getTime(date):
    rslt = re.search(r'\b\d{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函数式编程指南(三):迭代器详解
Jun 24 Python
Python中模块string.py详解
Mar 12 Python
Python hashlib模块用法实例分析
Jun 12 Python
python从子线程中获得返回值的方法
Jan 30 Python
python机器学习库scikit-learn:SVR的基本应用
Jun 26 Python
Python实现个人微信号自动监控告警的示例
Jul 03 Python
使用Python轻松完成垃圾分类(基于图像识别)
Jul 09 Python
Django连接数据库并实现读写分离过程解析
Nov 13 Python
django框架两个使用模板实例
Dec 11 Python
python 等差数列末项计算方式
May 03 Python
python设置 matplotlib 正确显示中文的四种方式
May 10 Python
Python中的协程(Coroutine)操作模块(greenlet、gevent)
May 30 Python
python逐行读取文件内容的三种方法
Jan 20 #Python
c++生成dll使用python调用dll的方法
Jan 20 #Python
python中getattr函数使用方法 getattr实现工厂模式
Jan 20 #Python
python字符串加密解密的三种方法分享(base64 win32com)
Jan 19 #Python
python实现人人网登录示例分享
Jan 19 #Python
使用BeautifulSoup爬虫程序获取百度搜索结果的标题和url示例
Jan 19 #Python
压缩包密码破解示例分享(类似典破解)
Jan 17 #Python
You might like
php实现12306余票查询、价格查询示例
2014/04/17 PHP
使用ob系列函数实现PHP网站页面静态化
2014/08/13 PHP
ThinkPHP中html:list标签用法分析
2016/01/09 PHP
Yii框架引用插件和ckeditor中body与P标签去除的方法
2017/01/19 PHP
Jquery模仿Baidu、Google搜索时自动补充搜索结果提示
2013/12/26 Javascript
jQuery鼠标悬浮链接弹出跟随图片实例代码
2016/01/08 Javascript
深入理解jquery自定义动画animate()
2016/05/24 Javascript
ionic环境配置及问题详解
2017/06/27 Javascript
JS按钮闪烁功能的实现代码
2017/07/21 Javascript
VueJs组件之父子通讯的方式
2018/05/06 Javascript
Vue中使用webpack别名的方法实例详解
2018/06/19 Javascript
JS实现数组去重,显示重复元素及个数的方法示例
2019/01/21 Javascript
layer弹出层自适应高度,垂直水平居中的实现
2019/09/16 Javascript
webpack打包html里面img后src为“[object Module]”问题
2019/12/22 Javascript
在vue项目中引用Antv G2,以饼图为例讲解
2020/10/28 Javascript
Python编程之变量赋值操作实例分析
2017/07/24 Python
Python使用装饰器进行django开发实例代码
2018/02/06 Python
Python 调用 Windows API COM 新法
2019/08/22 Python
python 命令行传入参数实现解析
2019/08/30 Python
在django-xadmin中APScheduler的启动初始化实例
2019/11/15 Python
Python-Flask:动态创建表的示例详解
2019/11/22 Python
Mac 使用python3的matplot画图不显示的解决
2019/11/23 Python
python通过nmap扫描在线设备并尝试AAA登录(实例代码)
2019/12/30 Python
html5指南-5.使用web storage存储键值对的数据
2013/01/07 HTML / CSS
全球知名旅游社区法国站点:TripAdvisor法国
2016/08/03 全球购物
美国杰西潘尼官网:JCPenney
2019/06/12 全球购物
js正则匹配markdown里的图片标签的实现
2021/03/24 Javascript
市场营销毕业生自荐信
2013/11/23 职场文书
党支部公开承诺践诺书
2014/03/28 职场文书
大学生学雷锋活动总结
2014/06/26 职场文书
工商管理专业毕业生自我鉴定2014
2014/10/04 职场文书
2014年生产管理工作总结
2014/12/23 职场文书
2015年办公室工作总结范文
2015/03/31 职场文书
《蚂蚁和蝈蝈》教学反思
2016/02/22 职场文书
HTML+css盒子模型案例(圆,半圆等)“border-radius” 简单易上手
2021/05/10 HTML / CSS
深入浅析Django MTV模式
2021/09/04 Python