Python_POP3自动收取邮件脚本

import poplib
from email.parser import Parser
import csv


class Email_pop3(object):
    def __init__(self):
        self.port = 995
        self.addr = "pop.exmail.qq.com"

    def email_handle(self, user, pwd, send_add, send_time):
        # CSV
        f = open(user + '.csv', 'a+', encoding='utf-8-sig', newline='')
        csv_writer = csv.writer(f)
        csv_writer.writerow(["发件人", "时间", "主题", "内容"])
        # 登陆
        server = poplib.POP3(self.addr)
        server.user(user)
        server.pass_(pwd)
        print('邮件总数:%s | 空间大小:%s' % server.stat())
        resp, mails, octets = server.list()
        print('邮件列表:', mails)
        for index in range(len(mails), -1, -1):
            # 状态/内容/容量
            resp, lines, octes = server.retr(index)
            # TODO 编码处理需完善
            try:
                msg_content = b'\r\n'.join(lines).decode('utf-8')
            except UnicodeDecodeError as e:
                try:
                    msg_content = b'\r\n'.join(lines).decode('gb2312')
                except UnicodeDecodeError as e:
                    try:
                        msg_content = b'\r\n'.join(lines).decode('gbk')
                    except UnicodeDecodeError as e:
                        msg_content = b'\r\n'.join(lines).decode('gb18030')
            # 内容解析Message内容
            msg = Parser().parsestr(text=msg_content)
            From = msg.get('From', '')
            To = msg.get('To', '')
            Date = msg.get('Date', '')
            Subject = msg.get('Subject', '')
            content = msg.get_payload()
            # 筛选条件
            if send_add in From and send_time in Date:
                for par in msg.walk():
                    if not par.is_multipart():
                        try:
                            data = par.get_payload(decode=True).decode()
                        except Exception as e:
                            data = par.get_payload(decode=True)
                csv_writer.writerow([From, Date, Subject, data])
                print(From, Date, 'Qualified, inserted successfully')
            else:
                print(From, Date, 'Unqualified insert failed')
            if not send_time in Date:
                break


obj = Email_pop3()
# 具体月份之后 "Mar 2021"/具体年 "2021"
obj.email_handle("user", "password", '发件人', '时间')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值