python邮件发送接收
接收邮件
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邮件发送接收的更多相关文章
- centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本)
centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本) ##################### sendmail.py begin ######## ...
- Python 邮件发送
python发送各类邮件的主要方法 python中email模块使得处理邮件变得比较简单,今天着重学习了一下发送邮件的具体做法,这里写写自己的的心得,也请高手给些指点. 一.相关模块介绍 ...
- Python邮件发送脚本(Linux,Windows)通用
脚本 #!/usr/bin/python #-*- coding:utf-8 -*- #Python Mail for chenglee #if fileformat=dos, update file ...
- python邮件发送自动化测试报告
话不多说直接贴代码 # encoding: utf-8import smtplib #发送邮件模块from email.mime.text import MIMEText #邮件内容from emai ...
- python邮件发送:普通文本、html、添加附件
# -*- coding: utf-8 -*- # @Time : 2019/9/19 13:46 # @Author : HuangWenjun # @Email : 350920551@qq.co ...
- python邮件发送脚本
转自:http://phinecos.cnblogs.com/ #!/usr/bin/python #coding=utf-8 #@author:dengyike #@date:2010-09-28 ...
- python邮件发送
'''qq邮件与其他邮件有所不同,下以我的qq邮件为例(切勿转载):''' import osimport smtplibfrom email.mime.text import MIMEText # ...
- Python邮件发送源码
-- coding:utf-8 -- i = 0 while i < 10: #发送十次 import smtplib from email.mime.text import MIMEText ...
- python 邮件发送 脚本
import smtplib from email.header import Header from email.mime.text import MIMEText from_addr = 'XXX ...
随机推荐
- 2016 Multi-University Training Contest 5 1012 World is Exploding 树状数组+离线化
http://acm.hdu.edu.cn/showproblem.php?pid=5792 1012 World is Exploding 题意:选四个数,满足a<b and A[a]< ...
- Handler笔记
5.Handler内存泄露 在一个Activity里面,如果没有静态地创建一个Handler,有可能导致内存泄露. 因为Hander和Looper绑定,如果looper的MessageQueue有消息 ...
- Red5下的room
http://blog.csdn.net/whycold/article/details/6142475 package com.test; import java.util.ArrayList;im ...
- Linux平台部署varnish 高性能缓存服务器
一:varnish部署前准备: 1.1相关软件以及系统,web服务 系统要求:Centos 6(以上) (64位) 相关中间件:varnish-4.0.2 1.2相关系统依赖包安装检查准备 1.2.1 ...
- C#中的ref和out的区别
转载原地址 http://www.cnblogs.com/gjahead/archive/2008/02/28/1084871.html ref和out的区别在C# 中,既可以通过值也可以通过引用传递 ...
- LCA算法
LCA算法: LCA(Least Common Ancestor),顾名思义,是指在一棵树中,距离两个点最近的两者的公共节点.也就是说,在两个点通往根的道路上,肯定会有公共的节点,我们就是要求找到公共 ...
- JS 命名空间 实现方式 收集
一. 对象注册式 // 声明一个全局对象Namespace,用来注册命名空间Namespace = new Object(); // 全局对象仅仅存在register函数,参数为名称空间全路径,如&q ...
- NHibernate - ICriteria 查询
http://blog.knowsky.com/213234.htm http://blog.chinaunix.net/uid-20463341-id-1673509.html http://www ...
- Oracle_11g_R2安装详解_for_Windows_7
Oracle 11g R2安装全攻略 - For Windows 7 图文教程 1.下载Oracle 11g R2的Windows版本,官方下载地址如下: http://download.oracle ...
- delphi CoolBar这个怎么弄没了
CoolBar这个怎么弄没了 像Windows这样的 procedure TForm1.Button1Click(Sender: TObject); begin CoolBar1.Fix ...