python发送邮件接收邮件示例分享_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()

时间: 2024-09-20 08:39:27

python发送邮件接收邮件示例分享_python的相关文章

python列表操作使用示例分享_python

复制代码 代码如下: Python 3.3.4 (v3.3.4:7ff62415e426, Feb 10 2014, 18:13:51) [MSC v.1600 64 bit (AMD64)] on win32Type "copyright", "credits" or "license()" for more information.>>> cast=["cleese","palin",

python局域网ip扫描示例分享_python

复制代码 代码如下: #!/usr/bin/python# -*- coding: utf-8 -*- from scapy.all import *from time import ctime,sleepimport threadingTIMEOUT = 4conf.verb=0 def pro(cc,handle): dst = "192.168.1." + str(cc) packet = IP(dst=dst, ttl=20)/ICMP() reply = sr1(packet

python list转dict示例分享_python

需求:['1:a','2:b','3:c'] 转换为 {'1′: 'a','3′: 'c','2′: ''} 复制代码 代码如下: a = {}b = ['1:a','2:b','3:c']map(lambda x:a.setdefault(x.split(':')[0], x.split(':')[1]), b)print a{'1': 'a', '3': 'c', '2': 'b'}

python使用cookielib库示例分享_python

该模块主要功能是提供可存储cookie的对象.使用此模块捕获cookie并在后续连接请求时重新发送,还可以用来处理包含cookie数据的文件. 这个模块主要提供了这几个对象,CookieJar,FileCookieJar,MozillaCookieJar,LWPCookieJar. 1. CookieJar CookieJar对象存储在内存中. 复制代码 代码如下: >>> import urllib2>>> import cookielib>>> c

python实现人人网登录示例分享_python

复制代码 代码如下: import reimport urllib2import cookielib def renren():    cj = cookielib.LWPCookieJar()    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))    email = ''    pwd   = ''     #登录..    print 'login......'    url = "http://www.renr

python抓取网页内容示例分享_python

复制代码 代码如下: import socketdef open_tcp_socket(remotehost,servicename):    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)    portnumber=socket.getservbyname(servicename,'tcp')    s.connect((remotehost,portnumber))    return smysocket=open_tcp_socket

linux系统使用python获取cpu信息脚本分享_python

linux系统使用python获取cpu信息脚本分享 复制代码 代码如下: #!/usr/bin/env Pythonfrom __future__ import print_functionfrom collections import OrderedDictimport pprint def CPUinfo():    ''' Return the information in /proc/CPUinfo    as a dictionary in the following format:

python使用PyV8执行javascript代码示例分享_python

安装相应的库,我使用的是PyV8 需要注意的是里面写的function函数需要用()括起来 复制代码 代码如下: import PyV8 class Test():     def js(self):        ctxt = PyV8.JSContext()        ctxt.enter()               func = ctxt.eval('''(function(){return '###'})''')        print func()        print

python实现代码行数统计示例分享_python

复制代码 代码如下: #!/usr/bin/python '''        File      : count.py        Author    : Mike        E-Mail    : Mike_Zhang@live.com'''import sys,os extens = [".c",".cpp",".hpp",".h"]linesCount = 0filesCount = 0 def funCount