python迁移邮件<仅做记录>

<脚本之初的原因是需要做邮件平移,并且已读,未读的状态一致.所以做了这个脚本>

#!/usr/bin/python
# -*- coding: utf-8 -*-
#Filename: testemail.py

import sys
import os
import imaplib
import time
import re
import cPickle as p

command=("status","qianyi","help")
error_log=‘errorUser.log‘
corr_user=‘correctuser.txt‘
default_dir=os.getcwd()

# def testServer():
#     try:
#         M=imaplib.IMAP4(argv[0])
#         M.logout()
#         return True
#     except Exception,ex:
#         return ex

def runTestOldMailbox(*argv):
    try:
        if argv[3].upper()==‘ON‘:
            testMailServer=imaplib.IMAP4_SSL(argv[0])
        else:
            testMailServer=imaplib.IMAP4(argv[0])
        mLogin=testMailServer.login(argv[1],argv[2])
        # print mLogin
        if mLogin[0]==‘OK‘:
            testMailServer.logout()
            return True
    except Exception,ex:
        return ex

def qiyiold(*argv):
    try:
        print ‘start‘
        uid_temp_list=[]
        mailbox_temp=""
        oldMailServer=argv[0]
        oldEmailAddress=argv[1]
        oldPassWord=argv[2]
        oldSsl_check=argv[3]

        newMailServer=argv[4]
        newEmailAddress=argv[5]
        newPassWord=argv[6]
        newSsl_check=argv[7]

        if oldSsl_check.upper()==‘ON‘:
            oldemail_M=imaplib.IMAP4_SSL(oldMailServer)
        else:
            oldemail_M=imaplib.IMAP4(oldMailServer)

        if newSsl_check.upper()==‘ON‘:
            newemail_M=imaplib.IMAP4_SSL(newMailServer)
        else:
            newemail_M=imaplib.IMAP4(newMailServer)

        oldemail_M.login(oldEmailAddress,oldPassWord)
        newemail_M.login(newEmailAddress,newPassWord)

        maildir_l=mail_dir(oldemail_M.list())
        userNumMail=0
        userAllMail=0
        oldemail_M.noop()
        newemail_M.noop()

        for mailbox in maildir_l:
            userNumMail=int(oldemail_M.select(mailbox)[1][0])
            userAllMail+=userNumMail
            print ‘<%s> <%s> <%s>‘%(oldEmailAddress,mailbox,userNumMail)
        print ‘User: <%s> EmailNum: <%s>.‘%(oldEmailAddress,userAllMail)

        print ‘Start qianyi mail....‘

        for mailbox in maildir_l:
            oldemail_M.select(mailbox)
            #判断是否存在文件夹,不存在则进行创建
            if newemail_M.select(mailbox)[0]<>‘OK‘:
                print ‘Not mailbox <%s>, Create mailbox <%s>.‘%(mailbox,newemail_M.create(mailbox)[1])
                # newemail_M.create(mailbox)
                newemail_M.select(mailbox)

            old_typ_n,old_data_n=newemail_M.search(None,‘ALL‘)
            oldmailid_n=old_data_n[0].split()
            userNumMail=int(oldemail_M.select(mailbox)[1][0])
            uidlist = panDuanUserBox(oldMailServer,oldEmailAddress,mailbox)
            uid_temp_list=uidlist
            typ,data=oldemail_M.search(None,‘SEEN‘)
            for num in data[0].split():
                typ,datauid=oldemail_M.fetch(num,‘UID‘)
                uid=datauid[0].split(‘ ‘)[2][0:-1]
                if (uid in uidlist):
                    continue
                else:
                    print ‘Start downloading...<%s><%s>‘%(mailbox,num)
                    #实现无痕取信,不影响原来服务器上面邮箱中邮件的状态
                    typ,mdata=oldemail_M.fetch(num,‘(UID BODY.PEEK[])‘)
                    print ‘download success...‘
                    print ‘Start upload...‘

                    if len(mdata[0][1])<1:
                        print ‘<%s> mailbox,num <%s> len=0,continue.‘%(mailbox,num)
                        continue
                    newemail_M.select(mailbox)
                    try:
                        newemail_M.append(mailbox,‘‘,imaplib.Time2Internaldate(time.time()),mdata[0][1])
                    except Exception,ex:
                        print ‘upload error:<%s><%s><%s><%s>‘%(oldEmailAddress,mailbox,num,ex)
                    uidlist.append(uid)
                    uid_temp_list=uidlist

            new_typ_n,new_data_n=newemail_M.search(None,‘ALL‘)
            newmailid_n=new_data_n[0].split()
            datalist=list(set(oldmailid_n)^set(newmailid_n))
            for num in datalist:
                newemail_M.store(num,‘+FLAGS‘,‘\SEEN‘)
            typ,data=oldemail_M.search(None,‘UNSEEN‘)

            for num in data[0].split():
                typ,datauid=oldemail_M.fetch(num,‘UID‘)
                uid=datauid[0].split(‘ ‘)[2][0:-1]
                if(uid in uidlist):
                    continue
                else:
                    print ‘Start downloading...<%s><%s>‘%(mailbox,num)
                    typ,mdata=oldemail_M.fetch(num,‘(UID BODY.PEEK[])‘)
                    print ‘download success...‘
                    print ‘Start upload...‘
                    # print data
                    # print mdata
                    if len(mdata[0][1])<1:
                        print ‘<%s> mailbox,num <%s> len=0,continue.‘%(mailbox,num)
                        continue
                    newemail_M.select(mailbox)
                try:
                    newemail_M.append(mailbox,‘‘,imaplib.Time2Internaldate(time.time()),mdata[0][1])
                except Exception,ex:
                    print ‘upload error:<%s><%s><%s><%s>‘%(oldEmailAddress,mailbox,num,ex)
                uidlist.append(uid)
                uid_temp_list=uidlist
            writeuid(oldMailServer,oldEmailAddress,mailbox,uidlist)
        return True
    except Exception,ex:
        return ex
    finally:
        writeuid(oldMailServer,oldEmailAddress,mailbox,uid_temp_list)

#将UID写入到文件中.以做记录,UID是邮件的唯一标识.可用于标识邮件是否已读.未读.
def writeuid(oldserver,oldname,mailbox,uidlist):
    # print os.getcwd()
    temppath=os.path.join(default_dir,‘temp‘).replace(‘\\‘,‘/‘)
    os.chdir(temppath)
    filename=oldname+mailbox
    f=file(filename,‘w‘)
    p.dump(uidlist,f)
    f.close()
    os.chdir(default_dir)

##判断是否有此文件夹
def panDuanUserBox(*argv):
    uidlist=[]
    # print ‘-------------------------------‘
    # print default_dir
    # os.chdir(default_dir)
    temppath=os.path.join(default_dir,‘temp‘).replace(‘\\‘,‘/‘)
    # print os.getcwd()
    if(os.path.exists(temppath)):
        os.chdir(temppath)
        filename=argv[1]+argv[2]
        if(os.path.isfile(filename)):
            f=file(filename)
            uidlist=p.load(f)
            os.chdir(default_dir)
            return uidlist
        else:
            os.chdir(default_dir)
            return uidlist
    else:
        os.mkdir(‘temp‘)
        os.chdir(default_dir)
        return uidlist

#用于排列邮件夹列表
def mail_dir(mlist):
    mail_list=[]
    for listone in mlist[1]:
        mail_list.append(listone.strip(‘"‘).split(‘"‘)[-1].strip(‘ ‘))
    return mail_list
时间: 2024-10-11 02:23:25

python迁移邮件<仅做记录>的相关文章

网站被攻击的请求,仅做记录

今天我们的网站被攻击,拦截请求中包含了以下内容.仅以为记. <input onfocus="document.write(String.fromCharCode(60,115,99,114,105,112,116,62,...60,47,115,99,114,105,112,116,62))" style="width:1px;height:1px;border:0;" autofocus="" value="loading...

阿里百川地址,趣拍iOS及andriod SDK--视频美颜,各种滤镜,仅做记录

阿里百川地址, http://baichuan.taobao.com/portal/doc?articleId=500 趣拍SDK http://www.qupai.me/sdk.html 版权声明:本文为博主原创文章,未经博主允许不得转载.

使用commons-net来下载文件(仅做记录)

使用 commons-net-3.6.jar public class ApacheFtpUtil { private Logger log = LoggerFactory.getLogger(ApacheFtpUtil.class); private String host; private String username; private String password; // 控制端口 private int port = 21; // 秒数 private int defaultTime

jdbc中对mysql数据库操作的简单封装--(仅做备忘记录)

本次使用jdbc中的mysql-connector-java-5.1.47-bin.jar的连接包,下载这个jar包放在javaee项目的WEB-INF/lib目录下,再把它作为外包jar包进入到libraries中,这样就可以使用mysql的jdbc接口了. 自己封装的代码中引入了两个自己字义的Exception:SqlSecureException.java package com.myproweb.exception; public class SqlSecureException ext

PHP扩展迁移为兼容PHP7记录

PHP7扩展编写的时候,提供的一些内核方法和之前的PHP之前的版本并不能完全兼容.有不少方法参数做了调整.下面是在迁移过程中遇到的一些问题.记录下来,避免大家再踩坑. PHP7扩展开发之hello word 白话PHP7扩展开发之创建对象 add_assoc_stringl 方法参数改为四个. add_assoc_stringl(parray, key, value, value_len); 迁移的时候,只要把最后一个参数删除即可. add_assoc_string 方法参数从四个改为了三个.

python 收发邮件

今天记录一下如何使用python收发邮件,知识要点在python内置的poplib和stmplib模块的使用上. 1. 准备工作 首先,我们需要有一个测试邮箱,我们使用新浪邮箱,而且要进行如下设置: 在新浪邮箱首页的右上角找到设置->更多设置,然后在左边选择"客户端/pop/imap/smtp": 最后,将Pop3/smtp服务的服务状态打开即可: 2. poplib接收邮件 首先,介绍一下poplib登录邮箱和下载邮件的一些接口: self.popHost = 'pop.sin

仅作记录,游标,级联删除,获取所有该外键的表名

以下内容只是部分原创,仅是之前收集到的知识.只做记录避免遗忘,具体出处已遗忘. 一.游标结构 总是遗忘游标的结构 declare PeriodDataCursor cursor for select ID , ClassTime from @temptable order by [ClassTime] desc open PeriodDataCursor fetch next from PeriodDataCursor into @ID , @firstClsTime while(@@FETCH

python收取邮件(腾讯企业邮箱)

记录下我用python登入腾讯企业邮箱收取邮件 一.要用python收取邮件先要会3个类 imaplib  用来收取邮件 imaplib 里面我们注意几个方法: login  使用明文密码识别客户端.该密码将被引用. select 选择一个邮箱.返回的数据是邮箱中的邮件计数 (EXISTS响应).默认邮箱是'INBOX'.如果 设置了只读标志,则不允许对邮箱进行修改. search 搜索邮箱以查找匹配的邮件 BeautifulSoup 用来解析 text/html 和 txet/plain 类型

python发邮件

import smtplib from email.mime.text import MIMEText from email.header import Header # 第三方 SMTP 服务 mail_host="smtp.qq.com" #设置服务器 mail_user="xxxxxx" #用户名 mail_pass="plcfthkdtpoxcabh" #口令QQ需要授权码 sender = '[email protected]' rec