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入门篇之编程习惯与特点
Oct 17 Python
Python多进程同步简单实现代码
Apr 27 Python
python中pandas.DataFrame排除特定行方法示例
Mar 12 Python
python3 模拟登录v2ex实例讲解
Jul 13 Python
在Python程序员面试中被问的最多的10道题
Dec 05 Python
python中将字典形式的数据循环插入Excel
Jan 16 Python
django反向解析和正向解析的方式
Jun 05 Python
如何用Python合并lmdb文件
Jul 02 Python
Python发送邮件测试报告操作实例详解
Dec 08 Python
python验证码图片处理(二值化)
Nov 01 Python
pytorch cuda上tensor的定义 以及减少cpu的操作详解
Jun 23 Python
Pandas 数据编码的十种方法
Apr 20 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 URL地址获取函数代码(端口等) 推荐
2010/05/15 PHP
PHP中对用户身份认证实现两种方法
2011/06/04 PHP
PHP一致性hash分布式算法封装类定义与用法示例
2018/08/04 PHP
简单实用的PHP文本缓存类实例
2019/03/22 PHP
PHP pthreads v3使用中的一些坑和注意点分析
2020/02/21 PHP
php设计模式之正面模式实例分析【星际争霸游戏案例】
2020/03/24 PHP
js中call与apply的用法小结
2013/12/28 Javascript
jQuery实现输入框下拉列表树插件特效代码分享
2015/08/27 Javascript
轻松学习jQuery插件EasyUI EasyUI实现拖动基本操作
2015/11/30 Javascript
js实现兼容IE、Firefox的图片缩放代码
2015/12/08 Javascript
jQuery Mobile弹出窗、弹出层知识汇总
2016/01/05 Javascript
原生js编写焦点图效果
2016/12/08 Javascript
JavaScript BASE64算法实现(完美解决中文乱码)
2017/01/10 Javascript
JS去除字符串中空格的方法
2017/02/14 Javascript
js微信应用场景之微信音乐相册案例分享
2017/08/11 Javascript
Vue-router的使用和出现空白页,路由对象属性详解
2018/09/03 Javascript
解决cordova+vue 项目打包成APK应用遇到的问题
2019/05/10 Javascript
element中的$confirm的使用
2020/04/26 Javascript
[01:06:12]VP vs NIP 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
Python利用正则表达式实现计算器算法思路解析
2018/04/25 Python
一篇文章了解Python中常见的序列化操作
2019/06/20 Python
python实现七段数码管和倒计时效果
2019/11/23 Python
Python pyautogui模块实现鼠标键盘自动化方法详解
2020/02/17 Python
Python 3.8 新功能来一波(大部分人都不知道)
2020/03/11 Python
python 瀑布线指标编写实例
2020/06/03 Python
浅谈django框架集成swagger以及自定义参数问题
2020/07/07 Python
python中upper是做什么用的
2020/07/20 Python
python+selenium自动化实战携带cookies模拟登陆微博
2021/01/19 Python
Exoticca英国:以最优惠的价格提供豪华异国情调旅行
2018/10/18 全球购物
HolidayLettings英国:预订最好的度假公寓、别墅和自助式住宿
2019/08/27 全球购物
大学生毕业鉴定
2014/01/31 职场文书
旅游管理毕业生自荐书
2014/02/02 职场文书
咖啡店创业计划书范文
2014/09/15 职场文书
2016年“12.3”国际残疾人日活动总结
2016/04/01 职场文书
Go Gin实现文件上传下载的示例代码
2021/04/02 Golang
2021-4-5课程——SQL Server查询【3】
2021/04/05 SQL Server