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

(0)

相关推荐

  • python监控网站运行异常并发送邮件的方法

    本文实例讲述了python监控网站运行异常并发送邮件的方法.分享给大家供大家参考.具体如下: 这是一个简单的python开发的监控程序,当指定网页状态不正常是通过smtp发送通知邮件 复制代码 代码如下: #!/usr/bin/env python # -*- coding: UTF-8 -*- #author  libertyspy import socket import smtplib import urllib mail_options = {     'server':'smtp.qq

  • python使用SMTP发送qq或sina邮件

    python使用qq邮箱(个人邮箱)发送邮件需开启qq邮箱的SMTP服务 在设置中开启pop3/SMTP服务,返回的密码就是之后代码中登录使用账户密码(在完整代码中标识了出来) 之后出现如下错误 复制代码 代码如下: smtplib.SMTPAuthenticationError: (530, 'Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/

  • python同时给两个收件人发送邮件的方法

    本文实例讲述了python同时给两个收件人发送邮件的方法.分享给大家供大家参考.具体分析如下: 该范例通过python内置的smtplib包发送邮件 import smtplib import string host = "localhost" fromclause = "a@b.com" toclause = "c@d.com, e@f.com" toclause = string.splitfields(toclause, ",&q

  • Python实现SMTP发送邮件详细教程

    简介 Python发送邮件的教程本人在网站搜索的时候搜索出来了一大堆,但是都是说了一大堆原理然后就推出了实现代码,我测试用给出的代码进行发送邮件时都不成功,后面找了很久才找到原因,这都是没有一个详细的环境调试导致,所以今天特出一个详细的教程,一步一步从环境调试到代码实现整一个教程,希望对还在苦苦寻找解决方法却迟迟不能得到有效解决的人员一点帮助. SMTP协议 首先了解SMTP(简单邮件传输协议),邮件传送代理程序使用SMTP协议来发送电邮到接收者的邮件服务器.SMTP协议只能用来发送邮件,不能用

  • Python实现给qq邮箱发送邮件的方法

    本文实例讲述了Python实现给qq邮箱发送邮件的方法.分享给大家供大家参考.具体实现方法如下: #-*-coding:utf-8-*- #========================================== # 导入smtplib和MIMEText #========================================== from email.mime.text import MIMEText import smtplib #===================

  • 基于python发送邮件的乱码问题的解决办法

    公司项目中需要通过后台发送邮件,邮件内容包括图片附件.如果通过PHPmailer发送,由于邮件服务器可能存在延迟现象,通过PHPmailer发送邮件,需要等待邮件发送成功后才能返回结果,这在实践中证明,有时发送邮件无法即时返回结果,影响用户体验. 于是我通过python发送邮件,PHP通过调用脚本方式来调用,这样执行脚本成功后立即返回,而无需判断邮件是否发送成功.只要成功执行脚本文件即向客户端返回成功标志.这样极大的提高了邮件发送速度,保证良好的用户体验效果. 但是,在通过python发送邮件,

  • python中使用smtplib和email模块发送邮件实例

    SMTP模块 这么多已定义的类中,我们最常用的的还是smtplib.SMTP类,就具体看看该类的用法:smtp实例封装一个smtp连接,它支持所有的SMTP和ESMTP操作指令,如果host和port参数被定义,则smtp会在初始化期间自动调用connect()方法,如果connect()方法失败,则会触发SMTPConnectError异常,timeout参数设置了超时时间.在一般的调用过程中,应该遵connetc().sendmail().quit()步骤. SMTP模块主要方法 下面我们来

  • python发送邮件示例(支持中文邮件标题)

    复制代码 代码如下: def sendmail(login={},mail={}):    '''\    @param login login['user'] login['passwd']    @param mail mail['to_addr'] mail['subject'] mail['content'] mail['attach']    '''    from datetime import datetime    from base64 import b64encode   

  • 二种python发送邮件实例讲解(python发邮件附件可以使用email模块实现)

    可以使用Python的email模块来实现带有附件的邮件的发送. SMTP (Simple Mail Transfer Protocol)邮件传送代理 (Mail Transfer Agent,MTA) 程序使用SMTP协议来发送电邮到接收者的邮件服务器.SMTP协议只能用来发送邮件,不能用来接收邮件.大多数的邮件发送服务器 (Outgoing Mail Server) 都是使用SMTP协议.SMTP协议的默认TCP端口号是25. SMTP协议的一个重要特点是它能够接力传送邮件.它工作在两种情况

  • python发送邮件的实例代码(支持html、图片、附件)

    第一段代码: 复制代码 代码如下: #!/usr/bin/python# -*- coding: utf-8 -*- import emailimport mimetypesfrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEText import MIMETextfrom email.MIMEImage import MIMEImageimport smtplib def sendEmail(authInfo, fromAdd

随机推荐