欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-08-14 08:58:01
接收邮件 复制代码 代码如下:import poplib,pdb,email,re,timefrom email import header pop_addr = r'...

接收邮件

复制代码 代码如下:

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()