imaplib 模块登陆163邮箱及下载

上一篇使用了pop3模块进行邮件的下载,模块提供的功能不如本篇的imap。

本篇将稍微深入的通过imap进行邮件的登陆和下载;

1、邮件登陆信息获取:

#!/usr/bin/env python
#-*- coding: utf-8 -*-
#filename:receive_imap_email.py

import imaplib, os, ConfigParser, re
import pprint


#进行用户的登陆,主要通过config文件进行主机名,用户名和密码的获取

def user_login(verbose=False):#verbose=False为函数参数定义的一种方式,在True的情况下执行
    #Read the config file
    config = ConfigParser.ConfigParser()
    config.read(r'D:\Python\tmp\config.txt')

    #Connect to the server
    hostname = config.get('server', 'hostname')
    if verbose:
        print 'Connecting to', hostname
        m = imaplib.IMAP4(hostname)

    #Login to the account
    username = config.get('account', 'username')
    passwd = config.get('account', 'passwd')
    if verbose:
        print 'Logging in as ', username
        m.login(username,passwd)
        print type(m)#返回instance
        return m
    
#对收件箱进行检查,列出对应的文件夹

def list_inbox():
    l_box = user_login(verbose=True)
    print type(l_box)
    try:
        typ, data = l_box.list()#注意这种赋值方式,返回值是状态和inbox,drafts,sent,trash等;即后者的两个元素依次赋给前者
        print 'Response code:', typ
        print 'Response:'
        pprint.pprint(data)
    finally:
        l_box.logout()


#user_login(verbose=True)#在True的情况下执行
list_inbox()

输出:

>>> ================================ RESTART ================================
>>> 
Connecting to imap.163.com
Logging in as  dxx_study
<type 'instance'>
<type 'instance'>
Response code: OK
Response:
['() "/" "INBOX"',
 '(\\Drafts) "/" "&g0l6P3ux-"',
 '(\\Sent) "/" "&XfJT0ZAB-"',
 '(\\Trash) "/" "&XfJSIJZk-"',
 '(\\Junk) "/" "&V4NXPpCuTvY-"',
 '() "/" "&dcVr0mWHTvZZOQ-"',
 '() "/" "&Xn9USpCuTvY-"',
 '() "/" "&i6KWBZCuTvY-"',
 '() "/" "test"']

从以上可以看出,编码将是这个工作中的难点,因为邮件编码采用的是base64,并且还要区分发件人的编码,目前已遇到的主要有utf-8,这个一般不处理,直接输出,其次是gb2312,再次是gbk,或者英文的直接ascii。

2、邮件解码

对于解码部分又分为,邮件标题和发件人,以及邮件正文。

下面再实例记录下处理的一些方法和技巧:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#filename:receive_imap_email.py

import imaplib, os, ConfigParser, re
import pprint, sys, email, string

#reload(sys)#设置为命令窗口cmd输出
#sys.setdefaultencoding('gbk')

def user_login(verbose=False):#verbose=False为函数参数定义的一种方式,在True的情况下执行
    #Read the config file
    config = ConfigParser.ConfigParser()
    config.read(r'D:\Python\tmp\config.txt')

    #Connect to the server
    hostname = config.get('server', 'hostname')
    if verbose:
        print 'Connecting to', hostname
        m = imaplib.IMAP4(hostname)

    #Login to the account
    username = config.get('account', 'username')
    passwd = config.get('account', 'passwd')
    if verbose:
        print 'Logging in as ', username
        m.login(username,passwd)
        
        return m
    


def list_inbox():#罗列收件箱的子目录
    l_box = user_login(verbose=True)
    try:
        typ, data = l_box.list()#注意这种赋值方式,返回值是状态和inbox,drafts,sent,trash等
        print 'Response code:', typ
        print 'Response:'
        pprint.pprint(data)#Mailbox names are in modified UTF7 character set.输出会出现乱码
    finally:
        l_box.logout()


def status_mailbox():
    stat_m = user_login(verbose=True)
    try:
        typ, data = stat_m.list()
        for line in data:#由于字符编码问题,暂无法去匹配对应收件箱的状态,未完待续
           print line
    finally:
        stat_m.logout()

def to_unicode(s, encoding):
    if encoding:
        return u
使用Python下载腾讯企业邮箱中的超大附件通常需要通过邮件客户端如Outlook等软件先将邮件的附件保存到本地,然后再通过Python代码读取本地文件并上传至服务器。直接使用Python下载超大附件可能存在一些限制,因为邮箱服务商往往限制了附件的大小,并且Python官方并没有直接提供对应的库来处理这种任务。 然而,有一些间接的方法可以尝试: 1. 使用IMAP协议,通过Python的`imaplib`库来连接到邮箱下载附件。但是请注意,如果附件大小超过了服务商设置的大小限制或者Python库处理大文件的能力,这种方法可能会失败。 2. 使用第三方库,如`yagmail`,它是一个扩展了邮件发送功能的库,可以发送邮件,但它的下载附件功能可能也受限于邮箱服务商对附件大小的限制。 一个简单的例子是使用`imaplib`来登录邮箱、查找邮件和下载附件: ```python import imaplib import email # 配置邮件服务器信息和登录信息 mail = imaplib.IMAP4_SSL('imap.qq.com') # 使用SSL连接 mail.login('your_email@qq.com', 'your_password') # 选择邮箱中的收件箱 mail.select('inbox') # 搜索邮件,这里以搜索最近的一封邮件为例 status, messages = mail.search(None, 'ALL') messages = messages[0].split() # 找到第一封邮件的ID status, data = mail.fetch(messages[0], '(RFC822)') # 解析邮件内容 raw_email = data[0][1] email_message = email.message_from_bytes(raw_email) # 找到附件部分并下载 for part in email_message.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('Content-Disposition') is None: continue filename = part.get_filename() filepath = f"./downloaded/{filename}" with open(filepath, 'wb') as f: f.write(part.get_payload(decode=True)) # 关闭IMAP连接 mail.close() mail.logout() ``` 请注意,以上代码仅为示例,实际操作时需要注意处理异常、安全性问题以及邮件服务商的限制。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值