imap - 如何删除消息

发布于 2024-09-08 13:49:24 字数 449 浏览 5 评论 0原文

如何删除邮箱中的邮件?我正在使用这个代码,但字母没有被删除。对不起我的英语。

def getimap(self,server,port,login,password):
    import imaplib, email
    box = imaplib.IMAP4(server,port)
    box.login(login,password)
    box.select()
    box.expunge()
    typ, data = box.search(None, 'ALL')
    for num in data[0].split() :
        typ, data = box.fetch(num, '(UID BODY[TEXT])')
        print num
        print data[0][1]
    box.close()
    box.logout()

How can I delete messages from the mail box? I am using this code, but the letters are not removed. Sorry for my English.

def getimap(self,server,port,login,password):
    import imaplib, email
    box = imaplib.IMAP4(server,port)
    box.login(login,password)
    box.select()
    box.expunge()
    typ, data = box.search(None, 'ALL')
    for num in data[0].split() :
        typ, data = box.fetch(num, '(UID BODY[TEXT])')
        print num
        print data[0][1]
    box.close()
    box.logout()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

烈酒灼喉 2024-09-15 13:49:24

这是删除收件箱中所有电子邮件的工作代码:

import imaplib
box = imaplib.IMAP4_SSL('imap.mail.microsoftonline.com', 993)
box.login("[email protected]","paswword")
box.select('Inbox')
typ, data = box.search(None, 'ALL')
for num in data[0].split():
   box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
box.close()
box.logout()

This is the working code for deleting all emails in your inbox:

import imaplib
box = imaplib.IMAP4_SSL('imap.mail.microsoftonline.com', 993)
box.login("[email protected]","paswword")
box.select('Inbox')
typ, data = box.search(None, 'ALL')
for num in data[0].split():
   box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
box.close()
box.logout()
◇流星雨 2024-09-15 13:49:24

我认为你应该首先标记要删除的电子邮件..例如:

for num in data[0].split():
   box.store(num, '+FLAGS', '\\Deleted')
box.expunge()

I think you should mark the emails to be deleted, first.. For example:

for num in data[0].split():
   box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
尐籹人 2024-09-15 13:49:24

这对我有用,而且速度非常快,因为我不会单独删除(存储)每封电子邮件,而是传递列表索引。这适用于个人 Gmail 和企业 Gmail(Google Apps for Business)。它首先选择要使用的文件夹/标签 m.list() 将显示所有可用的。然后,它会搜索一年以上的电子邮件,并移至垃圾箱。然后它用删除标志标记垃圾箱中的所有电子邮件并删除所有内容:

#!/bin/python

import datetime
import imaplib

m = imaplib.IMAP4_SSL("imap.gmail.com")  # server to connect to
print "Connecting to mailbox..."
m.login('gmail@your_gmail.com', 'your_password')

print m.select('[Gmail]/All Mail')  # required to perform search, m.list() for all lables, '[Gmail]/Sent Mail'
before_date = (datetime.date.today() - datetime.timedelta(365)).strftime("%d-%b-%Y")  # date string, 04-Jan-2013
typ, data = m.search(None, '(BEFORE {0})'.format(before_date))  # search pointer for msgs before before_date

if data != ['']:  # if not empty list means messages exist
    no_msgs = data[0].split()[-1]  # last msg id in the list
    print "To be removed:\t", no_msgs, "messages found with date before", before_date
    m.store("1:{0}".format(no_msgs), '+X-GM-LABELS', '\\Trash')  # move to trash
    print "Deleted {0} messages. Closing connection & logging out.".format(no_msgs)
else:
    print "Nothing to remove."

#This block empties trash, remove if you want to keep, Gmail auto purges trash after 30 days.
print("Emptying Trash & Expunge...")
m.select('[Gmail]/Trash')  # select all trash
m.store("1:*", '+FLAGS', '\\Deleted')  #Flag all Trash as Deleted
m.expunge()  # not need if auto-expunge enabled

print("Done. Closing connection & logging out.")
m.close()
m.logout()
print "All Done."

This is what works for me, and it is really fast as I don't delete each email individually (store) but pass the list index instead. This works for gmail personal as well as enterprise (Google Apps for Business). It first selects the folder/label to use m.list() will show you all available. It then searches for emails over a year old, and performs a move to trash. It then flags all the emails in trash with the delete flag and expunges everything:

#!/bin/python

import datetime
import imaplib

m = imaplib.IMAP4_SSL("imap.gmail.com")  # server to connect to
print "Connecting to mailbox..."
m.login('gmail@your_gmail.com', 'your_password')

print m.select('[Gmail]/All Mail')  # required to perform search, m.list() for all lables, '[Gmail]/Sent Mail'
before_date = (datetime.date.today() - datetime.timedelta(365)).strftime("%d-%b-%Y")  # date string, 04-Jan-2013
typ, data = m.search(None, '(BEFORE {0})'.format(before_date))  # search pointer for msgs before before_date

if data != ['']:  # if not empty list means messages exist
    no_msgs = data[0].split()[-1]  # last msg id in the list
    print "To be removed:\t", no_msgs, "messages found with date before", before_date
    m.store("1:{0}".format(no_msgs), '+X-GM-LABELS', '\\Trash')  # move to trash
    print "Deleted {0} messages. Closing connection & logging out.".format(no_msgs)
else:
    print "Nothing to remove."

#This block empties trash, remove if you want to keep, Gmail auto purges trash after 30 days.
print("Emptying Trash & Expunge...")
m.select('[Gmail]/Trash')  # select all trash
m.store("1:*", '+FLAGS', '\\Deleted')  #Flag all Trash as Deleted
m.expunge()  # not need if auto-expunge enabled

print("Done. Closing connection & logging out.")
m.close()
m.logout()
print "All Done."
千纸鹤 2024-09-15 13:49:24

以下代码打印一些消息头字段,然后删除消息。

import imaplib
from email.parser import HeaderParser
m = imaplib.IMAP4_SSL("your_imap_server")
m.login("your_username","your_password")
# get list of mailboxes
list = m.list()
# select which mail box to process
m.select("Inbox") 
resp, data = m.uid('search',None, "ALL") # search and return Uids
uids = data[0].split()    
mailparser = HeaderParser()
for uid in uids:
    resp,data = m.uid('fetch',uid,"(BODY[HEADER])")        
    msg = mailparser.parsestr(data[0][1])       
    print (msg['From'],msg['Date'],msg['Subject'])        
    print m.uid('STORE',uid, '+FLAGS', '(\\Deleted)')
print m.expunge()
m.close() # close the mailbox
m.logout() # logout 

The following code prints some message header fields and then delete message.

import imaplib
from email.parser import HeaderParser
m = imaplib.IMAP4_SSL("your_imap_server")
m.login("your_username","your_password")
# get list of mailboxes
list = m.list()
# select which mail box to process
m.select("Inbox") 
resp, data = m.uid('search',None, "ALL") # search and return Uids
uids = data[0].split()    
mailparser = HeaderParser()
for uid in uids:
    resp,data = m.uid('fetch',uid,"(BODY[HEADER])")        
    msg = mailparser.parsestr(data[0][1])       
    print (msg['From'],msg['Date'],msg['Subject'])        
    print m.uid('STORE',uid, '+FLAGS', '(\\Deleted)')
print m.expunge()
m.close() # close the mailbox
m.logout() # logout 
泪意 2024-09-15 13:49:24

如果您使用的是 GMail,则过程会有所不同:

  1. 将其移至 [Gmail]/Trash 文件夹。
  2. 从 [Gmail]/Trash 文件夹中将其删除(添加 \Delete 标志)

[Gmail]/Spam 和 [Gmail]/Trash 中的所有电子邮件将在 30 天后删除。
如果您从[Gmail]/垃圾邮件或[Gmail]/垃圾箱中删除邮件,该邮件将被永久删除。

还记得在设置标签“已删除”后调用EXPUNGE

If you are using GMail the process is a bit different:

  1. Move it to the [Gmail]/Trash folder.
  2. Delete it from the [Gmail]/Trash folder (Add \Delete flag)

All emails in [Gmail]/Spam and [Gmail]/Trash are deleted after 30 days.
If you delete a message from [Gmail]/Spam or [Gmail]/Trash, it will be deleted permanently.

Remember also to call EXPUNGE after setting the tag Deleted.

留一抹残留的笑 2024-09-15 13:49:24

这是我根据上面的代码编写的程序:

https://github.com/ AndrewDJohnson/py-purge-email/

import imaplib
import sys
import traceback
import datetime
import re
from getpass import getpass

"""
PyPurge Email V1.0
==================
Andrew Johnson
[email protected]
06 Nov 2019


This Python 3 program will scan an email account using IMAP for messages older than
a certain age and delete them.

Old email can be deleted from all folders or each folder.

Because of the length of time bulikng deleting takes, folders can be scanned first
then the deletions can be left running (which might take several hours for many
thousands of messages.)

After running this, you may need to "empty" your deleted items/Trash folder to recover the space.
With hotmail/live/outlook accounts (i.e. online Microsoft ones) you will need to manually empty "recoverable items" too.
This is done within the "deleted items" folder when viewing your webmail.

"""

#You can hardcode your IMAP settings here, or they can be entered interactively.
#If "user" is set to a non-empty value, it is assumed the other values are set
#and so they are not requested  interactively.
host = ''
#Port 993 is normally the port for SSL comms for IMAP
port = 993
user=''
password = ''

#This is a list of the 3 most common email providers.
imap_hosts=[["GMail","imap.gmail.com","Trash"],
            ["Hotmail, Live, Outlook","imap-mail.outlook.com","Deleted"],
            ["Yahoo","imap.mail.yahoo.com","Trash"]]
#We default to checking for email that is older than 1 year.
days_old=365
deleted_mail_folder_name="Trash"



#This expression and function parse the mailbox data returned by the IMAP server
list_response_pattern = re.compile(r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" (?P<name>.*)')
def parse_list_response(line):

    flags, delimiter, mailbox_name = list_response_pattern.match(line).groups()
    mailbox_name = mailbox_name.strip('"')
    if flags.lower().find("noselect") >= 0:
        mailbox_name=""  
    return (flags, delimiter, mailbox_name)

#This function will iterate through the folders on the IMAP server and check
#or delete email.
def do_folders(imap,days_old,check_or_del,deletion_list):
    #Confirm any deletion of emails.
    if check_or_del != "check":
        resp = input ("Are you sure you want to delete emails? (Enter 'Yes') to confirm)>>>")
        if resp.lower()!="yes":
            return

    #Get the folder list from the server
    resp, data = imap.list()
    totalMsgs = 0
    actioned= "Nothing to do!"
    if resp == 'OK':
        #Iterate through folders
        for mbox in data:
            flags, separator, name = parse_list_response(bytes.decode(mbox))
            #If mailbox name returned is empty, go to next entry.
            if name == "":
                continue
            # Select the mailbox for checking or deleting messages.
            print ("Checking folder: ",name)
            imap.select('"{0}"'.format(name), (check_or_del=="check"))

            #Search for messages older than the given date.
            before_date = (datetime.date.today() - datetime.timedelta(days_old)).strftime("%d-%b-%Y")  # date string, 
            resp, msgnums = imap.search(None, '(BEFORE {0})'.format(before_date))
            msg_count = len(msgnums[0].split())

            #Print the results
            print('{:<30} : {: d}'.format(name, msg_count))

            #Shall we check or delete?
            if (msg_count > 0):
                if (check_or_del=="check"):
                    #Ask the user if they want mail deleted from the folder found.
                    print ("Delete mail older than {0} in {1} folder? (Enter y to delete)>>> ".format(before_date, name))
                    resp=input("")

                    if resp.lower()=='y':
                        #Add the folder name to a list.
                        deletion_list.append (name)
                        totalMsgs = totalMsgs + msg_count

                    actioned="Total found to Delete:"
                    continue
                else:
                    actioned="Deleted: "
                    #Print a message telling the user about the time it might take!
                    if name in deletion_list or len(deletion_list) == 0:
                        totalMsgs = totalMsgs + msg_count                        
                        print (msg_count, "messages found with date before ", before_date, "will be moved to trash")
                        if (msg_count > 50000):
                            print ("This could take several hours!")
                        elif (msg_count > 5000):
                            print ("This could take an hour or more!")
                        elif (msg_count > 500):
                            print ("This could take a few minutes")

                        #Now mark the "found" messages as deleted using the IMAP library.    
                        imap.store("1:{0}".format(msg_count), '+FLAGS', '\\Deleted') 
                        continue
            else:
                #No messages found to delete so continue to next folder.
                continue

        print('{:<30} : {: d}'.format(actioned, totalMsgs))
        return (deletion_list)



folder = ''
deletion_list=[]


#Sign on message.
print ("*********--------****-----***************")
print ("* Python Email Purger - V1.0 - Nove 2019 *")
print ("*********--------****-----***************")
print (" ")

#Set some flags
exit_prog=False
input_needed=True

#Start a loop in case the user wants to have repeated runs of deleting messages!
while exit_prog==False:


    #Check if we already have some values from previous loop iteration
    if user != "":
        print ("Server:\t\t", host)
        print ("Username:\t",user)
        print ("Message Age:\t",days_old) 
        resp=input("Enter 'y' to use the values above>>> ")
        if resp != "y":
            user=""

    #Check if input values are already set and if they are not set,
    #read them in from the keyboard
    if user == "":
        while input_needed:
            #Get the host IMAP server domain etc.
            for i in range (0,len (imap_hosts)):
                print (i+1,imap_hosts[i][0], " - ",imap_hosts[i][1])
            input_needed=True            
            host_input=input("Enter imap server name number, as given above, or type the address>>> ")
            max_host_index=str(len(imap_hosts))
            if len (host_input)==1 and (host_input >"0") and (host_input <= max_host_index):
                host=imap_hosts[int(host_input)-1][1]
                #Set deleted items folder name.
                deleted_mail_folder_name=imap_hosts[int(host_input)-1][2]
                input_needed=False
            else:
                if len(host_input) < 10:
                    print ("Please enter a valid host address.")
                    input_needed=True
                else:
                    host=host_input
        user=input ("Username:")
        print ("Password:")
        #This is an attempt to read in the password without echo, but it
        #does not work when running in Windows GUI/IDLE
        password=getpass()

        #Get the required age of messages.
        input_needed=True
        while input_needed:
            input_needed=False
            resp = input("Deleted messages older than how many days? Default is '365'>>> ")
            if len (resp) > 0:
                days_old = int (resp)

            if days_old == 0:
                print ("You must enter a value greater than 0.")
                input_needed=True

    #Now connect to the server                              
    print ("Connecting to ",host,"...")
    imap = None

    try:
        # Create the IMAP Client
        imap = imaplib.IMAP4_SSL(host, port)
        # Login to the IMAP server
        resp, data = imap.login(user, password)
        #Check the server response.
        if resp == 'OK':
            print ("Logged in... Looking for messages older than", days_old, "days.")
            #Ask the user whether they want to delete messages in all folders, or
            #in selected folders.
            while not resp in ["c","a"]:
                resp = input ("Enter 'c' to check each folder, or 'a' to delete from all folders >>>")

            #Now call the function to check for and delete messages.
            if resp=="c":
                #Get folders and search for messages.
                deletion_list = do_folders(imap,days_old,"check", deletion_list)
                deletion_list = do_folders(imap,days_old,"delete", deletion_list)
            else:
                #Delete messages in selected folders
                deletion_list = do_folders(imap,days_old,"delete", deletion_list)

            if deleted_mail_folder_name!="":
                print("Emptying Trash & Expunge...")
                imap.select(deleted_mail_folder_name)  # select all trash
                imap.store("1:*", '+FLAGS', '\\Deleted')  #Flag all Trash as Deleted
                imap.expunge() 
    except:
        resp = input ("Something went wrong... enter 'd' to see details, otherwise just press 'Enter' to exit...")
        if resp=='d':
            print('Error was : {0}'.format(sys.exc_info()[0]))
            traceback.print_exc()
            print ("Are you any the wiser? :-)")

#    finally:

        resp = input ("Enter 'Y' to delete more messages.")
        if resp.lower()!='y':
            exit_prog=True;
            if imap != None:
                imap.logout()
            imap = None
            print ("Finished...")

Here is a program I wrote, based on the code above:

https://github.com/AndrewDJohnson/py-purge-email/

import imaplib
import sys
import traceback
import datetime
import re
from getpass import getpass

"""
PyPurge Email V1.0
==================
Andrew Johnson
[email protected]
06 Nov 2019


This Python 3 program will scan an email account using IMAP for messages older than
a certain age and delete them.

Old email can be deleted from all folders or each folder.

Because of the length of time bulikng deleting takes, folders can be scanned first
then the deletions can be left running (which might take several hours for many
thousands of messages.)

After running this, you may need to "empty" your deleted items/Trash folder to recover the space.
With hotmail/live/outlook accounts (i.e. online Microsoft ones) you will need to manually empty "recoverable items" too.
This is done within the "deleted items" folder when viewing your webmail.

"""

#You can hardcode your IMAP settings here, or they can be entered interactively.
#If "user" is set to a non-empty value, it is assumed the other values are set
#and so they are not requested  interactively.
host = ''
#Port 993 is normally the port for SSL comms for IMAP
port = 993
user=''
password = ''

#This is a list of the 3 most common email providers.
imap_hosts=[["GMail","imap.gmail.com","Trash"],
            ["Hotmail, Live, Outlook","imap-mail.outlook.com","Deleted"],
            ["Yahoo","imap.mail.yahoo.com","Trash"]]
#We default to checking for email that is older than 1 year.
days_old=365
deleted_mail_folder_name="Trash"



#This expression and function parse the mailbox data returned by the IMAP server
list_response_pattern = re.compile(r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" (?P<name>.*)')
def parse_list_response(line):

    flags, delimiter, mailbox_name = list_response_pattern.match(line).groups()
    mailbox_name = mailbox_name.strip('"')
    if flags.lower().find("noselect") >= 0:
        mailbox_name=""  
    return (flags, delimiter, mailbox_name)

#This function will iterate through the folders on the IMAP server and check
#or delete email.
def do_folders(imap,days_old,check_or_del,deletion_list):
    #Confirm any deletion of emails.
    if check_or_del != "check":
        resp = input ("Are you sure you want to delete emails? (Enter 'Yes') to confirm)>>>")
        if resp.lower()!="yes":
            return

    #Get the folder list from the server
    resp, data = imap.list()
    totalMsgs = 0
    actioned= "Nothing to do!"
    if resp == 'OK':
        #Iterate through folders
        for mbox in data:
            flags, separator, name = parse_list_response(bytes.decode(mbox))
            #If mailbox name returned is empty, go to next entry.
            if name == "":
                continue
            # Select the mailbox for checking or deleting messages.
            print ("Checking folder: ",name)
            imap.select('"{0}"'.format(name), (check_or_del=="check"))

            #Search for messages older than the given date.
            before_date = (datetime.date.today() - datetime.timedelta(days_old)).strftime("%d-%b-%Y")  # date string, 
            resp, msgnums = imap.search(None, '(BEFORE {0})'.format(before_date))
            msg_count = len(msgnums[0].split())

            #Print the results
            print('{:<30} : {: d}'.format(name, msg_count))

            #Shall we check or delete?
            if (msg_count > 0):
                if (check_or_del=="check"):
                    #Ask the user if they want mail deleted from the folder found.
                    print ("Delete mail older than {0} in {1} folder? (Enter y to delete)>>> ".format(before_date, name))
                    resp=input("")

                    if resp.lower()=='y':
                        #Add the folder name to a list.
                        deletion_list.append (name)
                        totalMsgs = totalMsgs + msg_count

                    actioned="Total found to Delete:"
                    continue
                else:
                    actioned="Deleted: "
                    #Print a message telling the user about the time it might take!
                    if name in deletion_list or len(deletion_list) == 0:
                        totalMsgs = totalMsgs + msg_count                        
                        print (msg_count, "messages found with date before ", before_date, "will be moved to trash")
                        if (msg_count > 50000):
                            print ("This could take several hours!")
                        elif (msg_count > 5000):
                            print ("This could take an hour or more!")
                        elif (msg_count > 500):
                            print ("This could take a few minutes")

                        #Now mark the "found" messages as deleted using the IMAP library.    
                        imap.store("1:{0}".format(msg_count), '+FLAGS', '\\Deleted') 
                        continue
            else:
                #No messages found to delete so continue to next folder.
                continue

        print('{:<30} : {: d}'.format(actioned, totalMsgs))
        return (deletion_list)



folder = ''
deletion_list=[]


#Sign on message.
print ("*********--------****-----***************")
print ("* Python Email Purger - V1.0 - Nove 2019 *")
print ("*********--------****-----***************")
print (" ")

#Set some flags
exit_prog=False
input_needed=True

#Start a loop in case the user wants to have repeated runs of deleting messages!
while exit_prog==False:


    #Check if we already have some values from previous loop iteration
    if user != "":
        print ("Server:\t\t", host)
        print ("Username:\t",user)
        print ("Message Age:\t",days_old) 
        resp=input("Enter 'y' to use the values above>>> ")
        if resp != "y":
            user=""

    #Check if input values are already set and if they are not set,
    #read them in from the keyboard
    if user == "":
        while input_needed:
            #Get the host IMAP server domain etc.
            for i in range (0,len (imap_hosts)):
                print (i+1,imap_hosts[i][0], " - ",imap_hosts[i][1])
            input_needed=True            
            host_input=input("Enter imap server name number, as given above, or type the address>>> ")
            max_host_index=str(len(imap_hosts))
            if len (host_input)==1 and (host_input >"0") and (host_input <= max_host_index):
                host=imap_hosts[int(host_input)-1][1]
                #Set deleted items folder name.
                deleted_mail_folder_name=imap_hosts[int(host_input)-1][2]
                input_needed=False
            else:
                if len(host_input) < 10:
                    print ("Please enter a valid host address.")
                    input_needed=True
                else:
                    host=host_input
        user=input ("Username:")
        print ("Password:")
        #This is an attempt to read in the password without echo, but it
        #does not work when running in Windows GUI/IDLE
        password=getpass()

        #Get the required age of messages.
        input_needed=True
        while input_needed:
            input_needed=False
            resp = input("Deleted messages older than how many days? Default is '365'>>> ")
            if len (resp) > 0:
                days_old = int (resp)

            if days_old == 0:
                print ("You must enter a value greater than 0.")
                input_needed=True

    #Now connect to the server                              
    print ("Connecting to ",host,"...")
    imap = None

    try:
        # Create the IMAP Client
        imap = imaplib.IMAP4_SSL(host, port)
        # Login to the IMAP server
        resp, data = imap.login(user, password)
        #Check the server response.
        if resp == 'OK':
            print ("Logged in... Looking for messages older than", days_old, "days.")
            #Ask the user whether they want to delete messages in all folders, or
            #in selected folders.
            while not resp in ["c","a"]:
                resp = input ("Enter 'c' to check each folder, or 'a' to delete from all folders >>>")

            #Now call the function to check for and delete messages.
            if resp=="c":
                #Get folders and search for messages.
                deletion_list = do_folders(imap,days_old,"check", deletion_list)
                deletion_list = do_folders(imap,days_old,"delete", deletion_list)
            else:
                #Delete messages in selected folders
                deletion_list = do_folders(imap,days_old,"delete", deletion_list)

            if deleted_mail_folder_name!="":
                print("Emptying Trash & Expunge...")
                imap.select(deleted_mail_folder_name)  # select all trash
                imap.store("1:*", '+FLAGS', '\\Deleted')  #Flag all Trash as Deleted
                imap.expunge() 
    except:
        resp = input ("Something went wrong... enter 'd' to see details, otherwise just press 'Enter' to exit...")
        if resp=='d':
            print('Error was : {0}'.format(sys.exc_info()[0]))
            traceback.print_exc()
            print ("Are you any the wiser? :-)")

#    finally:

        resp = input ("Enter 'Y' to delete more messages.")
        if resp.lower()!='y':
            exit_prog=True;
            if imap != None:
                imap.logout()
            imap = None
            print ("Finished...")
蒲公英的约定 2024-09-15 13:49:24

从收件箱中删除所有电子邮件。

## ---------------------------------------------------------------------------
#### Created by: James (Jamsey) P. Lopez
#### Created date: 11/28/2020
#### Modified date: 11/29/2020; 11/30/2020; 12/3/2020
## ---------------------------------------------------------------------------
import win32com.client, time

#### Setting email
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
m = messages.GetFirst()

#### Loop for emails     
for m in list(messages):
    sender = m.SenderEmailAddress
    EmailDate = m.ReceivedTime
    if sender == "":
        m.Delete()
        time.sleep(.25)
    else:
        print sender
        print EmailDate
        m.Delete()
        time.sleep(.25)

删除所有带有日期条件的电子邮件。
此程序将删除自当前日期起 20 天之前的所有电子邮件。
调整程序中变量 Dy 中的天数。例子。 DY = 20

## ---------------------------------------------------------------------------
#### Created by: James (Jamsey) P. Lopez
#### Created date: 11/28/2020
#### Modified date: 11/29/2020; 11/30/2020; 12/3/2020
## ---------------------------------------------------------------------------
import win32com.client, datetime, string, time
from datetime import datetime, date, timedelta

#### Setting email
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
m = messages.GetFirst()

############ The delete condition below
############ Creating the date that will determine which emails will be deleted
cur_date = datetime.today()

#### Days to keep and any emails older than 20 days will be deleted
#### Adjust the days to keep as needed
Dy = 20
datedays = cur_date-timedelta(days=Dy)
EndDy = "{}".format(datedays.strftime("%m/%d/%Y 00:00:00"))
EndDy = '"' + EndDy + '"'; ##print End30

#### Loop for emails     
for m in list(messages):
    sender = m.SenderEmailAddress

    EmailDate = m.ReceivedTime; ##print EmailDate
    EmailDate = datetime.strptime(str(EmailDate), '%m/%d/%y %H:%M:%S'); ##print EmailDate
    EmailDate = EmailDate.strftime('%m/%d/%Y %H:%M:%S'); ##print EmailDate
    EmailDate = '"' + EmailDate + '"'; ##print EmailDate;print End30

    if sender == "":
        print EmailDate
        m.Delete()
        time.sleep(.25)
    elif EmailDate < EndDy:
        print ("\nDeleted email = %(sender)s and date = %(EmailDate)s" % vars())
        print ("          because it is older than %(EndDy)s" % vars())
        print ("          which is %(Dy)s days older than today %(cur_date)s\n" % vars())
        m.Delete()
        time.sleep(.25)

Delete all emails from inbox.

## ---------------------------------------------------------------------------
#### Created by: James (Jamsey) P. Lopez
#### Created date: 11/28/2020
#### Modified date: 11/29/2020; 11/30/2020; 12/3/2020
## ---------------------------------------------------------------------------
import win32com.client, time

#### Setting email
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
m = messages.GetFirst()

#### Loop for emails     
for m in list(messages):
    sender = m.SenderEmailAddress
    EmailDate = m.ReceivedTime
    if sender == "":
        m.Delete()
        time.sleep(.25)
    else:
        print sender
        print EmailDate
        m.Delete()
        time.sleep(.25)

Delete all emails with date condition.
This program will delete all emails older that 20 days from the current date.
Adjust the days in variable Dy in program. example. DY = 20

## ---------------------------------------------------------------------------
#### Created by: James (Jamsey) P. Lopez
#### Created date: 11/28/2020
#### Modified date: 11/29/2020; 11/30/2020; 12/3/2020
## ---------------------------------------------------------------------------
import win32com.client, datetime, string, time
from datetime import datetime, date, timedelta

#### Setting email
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
m = messages.GetFirst()

############ The delete condition below
############ Creating the date that will determine which emails will be deleted
cur_date = datetime.today()

#### Days to keep and any emails older than 20 days will be deleted
#### Adjust the days to keep as needed
Dy = 20
datedays = cur_date-timedelta(days=Dy)
EndDy = "{}".format(datedays.strftime("%m/%d/%Y 00:00:00"))
EndDy = '"' + EndDy + '"'; ##print End30

#### Loop for emails     
for m in list(messages):
    sender = m.SenderEmailAddress

    EmailDate = m.ReceivedTime; ##print EmailDate
    EmailDate = datetime.strptime(str(EmailDate), '%m/%d/%y %H:%M:%S'); ##print EmailDate
    EmailDate = EmailDate.strftime('%m/%d/%Y %H:%M:%S'); ##print EmailDate
    EmailDate = '"' + EmailDate + '"'; ##print EmailDate;print End30

    if sender == "":
        print EmailDate
        m.Delete()
        time.sleep(.25)
    elif EmailDate < EndDy:
        print ("\nDeleted email = %(sender)s and date = %(EmailDate)s" % vars())
        print ("          because it is older than %(EndDy)s" % vars())
        print ("          which is %(Dy)s days older than today %(cur_date)s\n" % vars())
        m.Delete()
        time.sleep(.25)
沫雨熙 2024-09-15 13:49:24

这是我用来删除或保留 Outlook 收件箱文件夹中的电子邮件的流程工作流程。
管理电子邮件是一个持续的维护问题。
有时我有数千封电子邮件需要删除。
我创建了两个 python 程序,这将使我能够有效地管理这个流程工作流程。

首先 - 我编写一个 python 程序来创建文本和 CSV 文件。
文本和 CSV 文件包含两部分。

  1. 每封唯一电子邮件的计数。
  2. 唯一的发件人电子邮件地址。

其次 - 我编辑文本或 CSV 文件以创建两个文本文件。

  1. EmailsToKeep.txt。
    A. 我想保留且无删除条件的电子邮件。
    B. 我将手动管理这些电子邮件。
  2. EmailsToKeepForAtLeast30Days.txt。
    A. 我想根据变量 EndDy 的日期值保留或删除电子邮件。
    我将根据需要附加这两个文本文件。

第三 - 我编写了第二个 python 程序来根据四个条件删除或保留电子邮件。

  1. 删除没有电子邮件地址的电子邮件。

  2. 保留 EmailsToKeep.txt 文本文件中的电子邮件。

  3. 保留或删除 EmailsToKeepForAtLeast30Days.txt 文本文件中的电子邮件。
    A. 如果日期比变量 EndDy 的日期值新,则保留电子邮件。
    B. 如果日期早于变量 EndDy 的日期值,则删除电子邮件。

  4. 删除未包含在任何 EmailsToKeep.txt 或 EmailsToKeepForAtLeast30Days.txt 文本文件中的电子邮件。
    视频链接:https://youtu.be/bTgb3tO5r-8

     第一个 python 程序。
     ##------------------------------------------------ ----------------------------
     ## 创建者:James (Jamsey) P. Lopez
     ## 创建日期:2020 年 11 月 28 日
     ## 修改日期:2020年12月2日、2020年12月5日
     ## 
     #### 这是两个 python 程序中的第一个
     #### 管理电子邮件是一个持续维护的问题
     #### 有时我有数千封电子邮件需要删除
     #### 这个 python 程序将使我能够有效地管理这个流程工作流程
     ####
     #### 我将从收件箱文件夹中创建一个唯一电子邮件的字典
     #### 然后,创建一个 for 循环来创建 TXT 和 CSV 文件
     #### 我将编辑 TXT 或 CSV 文件以创建最终的文本文件
     #### EmailsToKeep.txt 和 EmailsToKeepForAtLeast30Days.txt
     #### A. EmailsToKeep.txt 用于我想要保留且无删除条件的电子邮件
     #### B. EmailsToKeepForAtLeast30Days.txt 用于我想要根据删除条件保留的电子邮件
     #### 我只会运行这个 python 程序一次
     #### 我将根据第二个 python 程序的需要附加这两个文本文件
     ##------------------------------------------------ ----------------------------
     导入 win32com.client,重新,时间,日期时间,字符串
    
     #################################################### ############################################
     ############ 将日期添加到文件名末尾
     start_c = datetime.datetime.now(); ##打印start_c
     c1 = (("%(start_c)s" % vars()).partition(' ')[0]); ##打印c1
     new_str = string.replace(c1, '-', '_');new_str = "_"+new_str;##print(new_str)
    
     #### 小路
     路径 =“S:\PythonProjects\EmailProject”
     B斜杠=“\\”
    
     #### 文本文件
     EmailT = "电子邮件文本文件"
     extt =“.txt”
     #### CSV 文件
     EmailC = "电子邮件CSV文件"
     extc =“.csv”
    
     #### 全文和 CSV 文件名
     EmailTextFile = ("%(path)s%(Bslash)s%(EmailT)s%(new_str)s%(extt)s" % vars());打印 EmailTextFile
     EmailCSVFile = ("%(path)s%(Bslash)s%(EmailC)s%(new_str)s%(extc)s" % vars());print ("%(EmailCSVFile)s\n" %vars( ))
    
     #### 设置电子邮件
     Outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
     收件箱 = Outlook.GetDefaultFolder(6)
     消息=收件箱.项目
     messages.Sort("[接收时间]", True)
     m = messages.GetFirst()
    
     #################################################### ############################################
     ############ 如果文本和 CSV 文件不存在则创建,如果存在则截断
     WriteEmailTextFile2=打开('%(EmailTextFile)s' % vars(),'w')
     WriteEmailTextFile2.close()
     WriteEmailCSVFile2=打开('%(EmailCSVFile)s' % vars(),'w')
     WriteEmailCSVFile2.close()
    
     #### 打开输出文本和 CSV 文件以附加数据
     WriteEmailTextFile=open('%(EmailTextFile)s' % vars(),'a')
     WriteEmailCSVFile=open('%(EmailCSVFile)s' % vars(),'a')
    
     #### 为收件箱中的所有电子邮件创建字典
     #### 这将创建独特的电子邮件以及重复的次数
     d = 字典()
    
     对于消息中的 m:
         尝试:
             发件人 = m.SenderEmailAddress
             发送者 = 发送者.lower()
             如果发件人在 d: 
                 ## 将电子邮件计数增加 1 
                 d[发件人] = d[发件人] + 1
             别的: 
                 ## 将电子邮件添加到字典中,计数为 1 
                 d[发件人] = 1
         除了:
             经过
    
     ##################################################
     #### 按发件人电子邮件地址对字典中的结果进行排序的代码
     从集合导入 OrderedDict 
     dict1 = OrderedDict(已排序(d.items()))
    
     #### 来自排序字典的 For 循环
     对于 dict1 中的键:
         #### d[key] 包含每个唯一发件人电子邮件地址的计数
         #### 键是唯一的发件人电子邮件地址
         KeySelection = (d[key], key); ##打印按键选择
         #### 将元组转换为字符串,以便我们可以拆分
         KeySelection = str(KeySelection); ##打印按键选择
    
         #### 拆分计数和发件人电子邮件地址
         #### 分割字符 = ,
         spl_char =“,”
         ## 电子邮件发件人重复的次数
         电子邮件计数 = KeySelection.rsplit(spl_char, 1)[0]
         ## 发件人电子邮件名称
         电子邮件名称 = KeySelection.rsplit(spl_char, 1)[-1]
         ##打印s1; ##打印s2
    
         ## 删除字符和空格
         ## 我需要的是发件人电子邮件地址重复的次数 (EmailCount)
         ## 和发件人电子邮件地址 (EmailName)
         EmailCount = re.sub(u"[(u') ]", '', EmailCount); ##打印电子邮件计数
         EmailName = re.sub(u"[(u') ]", '', EmailName); ##打印电子邮件名称
    
         ## 将行写入 TXT 和 CSV 文件
         line = ("%(EmailCount)s,%(EmailName)s\n" % vars())
         打印行
         WriteEmailTextFile.write(行)
         WriteEmailCSVFile.write(行)
         ##时间.睡眠(2)
    
     #### 关闭写入文件
     WriteEmailTextFile.close()
     WriteEmailCSVFile.close()
    
    
    
     第二个Python程序。
     ##------------------------------------------------ ----------------------------
     #### 创建者:James (Jamsey) P. Lopez
     #### 创建日期:2020 年 11 月 28 日
     #### 修改日期:2020年11月29日; 2020 年 11 月 30 日; 2020年12月3日
     #### 
     #### 这是两个 python 程序中的第二个
     #### 管理电子邮件是一个持续维护的问题
     #### 有时我有数千封电子邮件需要删除
     #### 这个 python 程序将使我能够有效地管理这个流程工作流程
     ####
     #### 这个程序使用两个文本文件来实现我的目标
     #### A. EmailsToKeep.txt 用于我想要保留且无删除条件的电子邮件
     #### 我将手动管理这些电子邮件
     #### B. EmailsToKeepForAtLeast30Days.txt 用于我想要根据删除条件保留的电子邮件
     #### 删除条件设置为变量End30
     #### 我将根据需要附加这两个文本文件
     ####
     #### 电子邮件维护条件
     #### 1. 删除没有电子邮件地址的电子邮件
     #### 2. 保留 EmailsToKeep.txt 文本文件中的电子邮件
     #### 3. 保留 EmailsToKeepForAtLeast30Days.txt 文本文件中的电子邮件
     #### A. 保留较新且等于变量 End30 值的电子邮件
     #### B. 删除早于变量 End30 值的电子邮件
     #### 4. 删除未包含在任何 EmailsToKeep.txt 或 EmailsToKeepForAtLeast30Days.txt 文本文件中的电子邮件
     ##------------------------------------------------ ----------------------------
     导入 win32com.client、日期时间、字符串、时间
     从日期时间导入日期时间、日期、时间增量
    
     #################################################### ############################################
     ############ 将日期添加到文件名末尾
     start_c = datetime.now(); ##打印start_c
     c1 = (("%(start_c)s" % vars()).partition(' ')[0]); ##打印c1
     new_str = string.replace(c1, '-', '_');new_str = "_"+new_str; ##打印(新的_str)
    
     #### 小路
     路径 =“S:\PythonProjects\EmailProject”
     B斜杠=“\\”
    
     #### 文本文件扩展名
     extt =“.txt”
    
     #### 要保留的现有电子邮件文本文件
     电子邮件KTF =“电子邮件保留”
     EmailKTFTextFile = ("%(path)s%(Bslash)s%(EmailKTF)s%(extt)s" % vars()); ##打印电子邮件KTFTextFile
    
     #### 现有电子邮件文本文件,用于在满足删除条件后删除特定电子邮件
     TextFile30Day = "电子邮件保留时间至少 30 天"
     EmailTextFile30Day = ("%(path)s%(Bslash)s%(TextFile30Day)s%(extt)s" % vars()); ##打印电子邮件文本文件30天
    
     #### 删除文本文件
     EmailT = "电子邮件已删除文本文件"
     EmailTextFile = ("%(path)s%(Bslash)s%(EmailT)s%(new_str)s%(extt)s" % vars()); ##打印电子邮件文本文件
    
     #################################################### ############################################
     ############ 创建删除文本文件(如果不存在)或截断(如果存在)
     WriteEmailTextFile2=打开('%(EmailTextFile)s' % vars(),'w')
     WriteEmailTextFile2.close()
    
     #### 打开删除文本文件来写入已删除的电子邮件
     WriteEmailTextFile=打开('%(EmailTextFile)s' % vars(),'a')
    
     ############ 下面的删除条件
     ############ 创建确定删除哪些电子邮件的日期
     cur_date = 日期时间.today()
    
     #### 保留天数
     镝=21
     datedays = cur_date-timedelta(天=Dy)
     EndDy = "{}".format(datedays.strftime("%m/%d/%Y 00:00:00"))
     EndDy = '"' + EndDy + '"'; ##打印结束30
    
     #### 计数器
     已读电子邮件总数 = 0
     已读邮件总数 = 0
     删除的电子邮件总数 = 0
    
     #### 设置电子邮件
     Outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
     收件箱 = Outlook.GetDefaultFolder(6)
     消息=收件箱.项目
     messages.Sort("[接收时间]", True)
     m = messages.GetFirst()
    
     #### 循环电子邮件     
     对于列表中的 m(消息):
         阅读的电子邮件总数 += 1
    
         电子邮件日期 = m.ReceivedTime; ##打印电子邮件日期
         EmailDate = datetime.strptime(str(EmailDate), '%m/%d/%y %H:%M:%S'); ##打印电子邮件日期
         EmailDate = EmailDate.strftime('%m/%d/%Y %H:%M:%S'); ##打印电子邮件日期
         电子邮件日期 = '"' + 电子邮件日期 + '"'; ##打印电子邮件日期;打印End30
    
         发件人 = m.SenderEmailAddress
         发件人 = 发件人.lower()
    
     ## 如果发件人 == "[电子邮件受保护]" 和 EmailDate <结束30:
     ## print ("\n AAAAAAA - 电子邮件 = %(发件人)s - 电子邮件日期 = %(EmailDate)s - %(End30)s 是截止日期" % vars())
     ## print ("\n BBBBBBB - %(EmailDate)s - %(End30)s - %(发件人)s" % vars())
    
         KTF = open('%(EmailKTFTextFile)s' % vars(), 'r')
         TF30 = open('%(EmailTextFile30Day)s' % vars(), 'r')
         如果发件人==“”:
             已读邮件总数 += 1
     ## print ("\n 1111 已删除 - 电子邮件发件人为空" % vars())
             line = ("无发件人: %(EmailDate)s\n" % vars())
             WriteEmailTextFile.write(行)
             m.Delete()
             删除的电子邮件总数 += 1
             睡眠时间(.25)
         KTF.read() 中的 elif 发送者:
             已读邮件总数 += 1
     ## print ("\n2222 %(sender)s : %(EmailDate)s - IS IN %(EmailKTF)s 文本文件" % vars())
             时间.睡眠(.25)
         TF30.read() 中的 elif 发送者:
             已读邮件总数 += 1
     ## print ("\n3333 %(sender)s : %(EmailDate)s - IS IN %(TextFile30Day)s 文本文件" % vars())
             如果电子邮件日期 <结束迪:
     ## print ("\n 4444 已删除 - %(sender)s : %(EmailDate)s : %(EndDy)s - IS IN %(TextFile30Day)s 文本文件" % vars())
                 line = ("%(发件人)s : %(EmailDate)s : %(EndDy)s - 位于电子邮件 30 天文本文件\n" % vars())
                 WriteEmailTextFile.write(行)
                 m.Delete()
                 删除的电子邮件总数 += 1
                 时间.睡眠(.25)
         别的:
             已读邮件总数 += 1
     ## print ("\n 5555 已删除 - %(sender)s : %(EmailDate)s - 不在 %(EmailKTF)s 和 %(TextFile30Day)s 文本文件中" % vars())
             line = ("%(sender)s : %(EmailDate)s - 不在任何已读取的电子邮件文本文件中\n" % vars())
             WriteEmailTextFile.write(行)
             m.Delete()
             删除的电子邮件总数 += 1
             睡眠时间(.25)
         KTF.close()
         TF30.close()
    
     WriteEmailTextFile.close()
    
     print '这是从 Outlook 收件箱读取的电子邮件总数 = ' + str(TotalEmailsRead)
     print '这是 if 语句中处理的电子邮件总数 = ' + str(TotalEmailInRead)
     print '这是 if 语句中删除的电子邮件总数 = ' + str(TotalEmailsDeleted)
    

This is the process workflow I use to either delete or keep emails in Outlook Inbox folder.
Managing emails is a constant maintenance issue.
Sometimes I have thousands of emails that I need to delete.
I have created two python programs which will enable me to efficiently manage this process workflow.

First - I write a python program to create a text and CSV file.
The text and CSV file contains two parts.

  1. A count for each unique email.
  2. The unique sender email address.

Second - I edit the text or CSV file to create two text files.

  1. EmailsToKeep.txt.
    A. Emails I want to keep with no delete condition.
    B. I will manage these emails manually.
  2. EmailsToKeepForAtLeast30Days.txt.
    A. Emails I want to keep or delete base on the date value of variable EndDy.
    I will append these two text files as needed.

Third - I write a second python program to delete or keep emails based on four conditions.

  1. Delete emails that have no email address.

  2. Keep emails that are in the EmailsToKeep.txt text file.

  3. Keep or delete emails that are in the EmailsToKeepForAtLeast30Days.txt text file.
    A. Keep emails if date is newer than the date value of variable EndDy.
    B. Delete emails if date is older than the date value of variable EndDy.

  4. Delete emails that were not included in any of the EmailsToKeep.txt or EmailsToKeepForAtLeast30Days.txt text files.
    Video link: https://youtu.be/bTgb3tO5r-8

     First python program.
     ## ---------------------------------------------------------------------------
     ## Created by: James (Jamsey) P. Lopez
     ## Created date: 11/28/2020
     ## Modified date: 12/2/2020, 12/5/2020
     ## 
     #### This is the first python program of two
     #### Managing emails is a constant maintenance issue
     #### Sometimes I have thousands of emails that I need to delete
     #### This python programs will enable me to efficiently manage this process workflow
     ####
     #### I will create a dictionary of unique emails from the Inbox folder
     #### Then, create a for loop to create the TXT and CSV files
     #### I will edit the TXT or CSV file to create the final text files
     ####    The EmailsToKeep.txt and the EmailsToKeepForAtLeast30Days.txt
     ####        A. EmailsToKeep.txt is for emails I want to keep with no delete condition
     ####        B. EmailsToKeepForAtLeast30Days.txt is for emails that I want to keep based on the delete condition
     #### I will run this python program only once
     #### I will append these two text files as needed for the second python program
     ## ---------------------------------------------------------------------------
     import win32com.client, re, time, datetime, string
    
     ############################################################################################
     ############ Adding date to end of file name
     start_c = datetime.datetime.now(); ##print start_c
     c1 = (("%(start_c)s" % vars()).partition(' ')[0]); ##print c1
     new_str = string.replace(c1, '-', '_');new_str = "_"+new_str;##print(new_str)
    
     #### Path
     path = "S:\PythonProjects\EmailProject"
     Bslash = "\\"
    
     #### Text file
     EmailT = "EmailsTextFile"
     extt = ".txt"
     #### CSV file
     EmailC = "EmailsCSVFile"
     extc = ".csv"
    
     #### Full Text and CSV file name
     EmailTextFile = ("%(path)s%(Bslash)s%(EmailT)s%(new_str)s%(extt)s" % vars());print EmailTextFile
     EmailCSVFile = ("%(path)s%(Bslash)s%(EmailC)s%(new_str)s%(extc)s" % vars());print ("%(EmailCSVFile)s\n" %vars())
    
     #### Setting email
     outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
     inbox = outlook.GetDefaultFolder(6)
     messages = inbox.Items
     messages.Sort("[ReceivedTime]", True)
     m = messages.GetFirst()
    
     ############################################################################################
     ############ Create Text and CSV file if it does not exist or truncate if it does exist
     WriteEmailTextFile2=open('%(EmailTextFile)s' % vars(),'w')
     WriteEmailTextFile2.close()
     WriteEmailCSVFile2=open('%(EmailCSVFile)s' % vars(),'w')
     WriteEmailCSVFile2.close()
    
     #### Opening output Text and CSV files to append data
     WriteEmailTextFile=open('%(EmailTextFile)s' % vars(),'a')
     WriteEmailCSVFile=open('%(EmailCSVFile)s' % vars(),'a')
    
     #### Creating dictionary for all the emails in inbox
     #### This will create unique emails and how many times they are repeated
     d = dict()
    
     for m in messages:
         try:
             sender = m.SenderEmailAddress
             sender = sender.lower()
             if sender in d: 
                 ## Increment count of emails by 1 
                 d[sender] = d[sender] + 1
             else: 
                 ## Add the emails to dictionary with count 1 
                 d[sender] = 1
         except:
             pass
    
     #################################################
     #### Code to sort results in dictionary by sender email address
     from collections import OrderedDict 
     dict1 = OrderedDict(sorted(d.items()))
    
     #### For loop from sorted dictionary
     for key in dict1:
         #### d[key] contains the count for each unique sender email address
         #### key is the unique sender email address
         KeySelection = (d[key], key); ##print KeySelection
         #### Converting tuple to string so we can split
         KeySelection = str(KeySelection); ##print KeySelection
    
         #### Splitting the count and sender email address
         #### The split character = ,
         spl_char = ","
         ## Number of times the email sender is repeated
         EmailCount = KeySelection.rsplit(spl_char, 1)[0]
         ## Senders email name
         EmailName = KeySelection.rsplit(spl_char, 1)[-1]
         ##print s1; ##print s2
    
         ## Deleting characters and space/s
         ## All I need is the number of times (EmailCount) the sender email address is repeated
         ## and the senders email address (EmailName)
         EmailCount = re.sub(u"[(u') ]", '', EmailCount); ##print EmailCount
         EmailName = re.sub(u"[(u') ]", '', EmailName); ##print EmailName
    
         ## Writing line to TXT and CSV file
         line = ("%(EmailCount)s,%(EmailName)s\n" % vars())
         print line
         WriteEmailTextFile.write(line)
         WriteEmailCSVFile.write(line)
         ##time.sleep(2)
    
     #### Closing write files
     WriteEmailTextFile.close()
     WriteEmailCSVFile.close()
    
    
    
     Second python program.
     ## ---------------------------------------------------------------------------
     #### Created by: James (Jamsey) P. Lopez
     #### Created date: 11/28/2020
     #### Modified date: 11/29/2020; 11/30/2020; 12/3/2020
     #### 
     #### This is the second python program of two
     #### Managing emails is a constant maintenance issue
     #### Sometimes I have thousands of emails that I need to delete
     #### This python programs will enable me to efficiently manage this process workflow
     ####
     #### This program uses two text files to accomplish my goal
     #### A. EmailsToKeep.txt is for emails I want to keep with no delete condition
     ####            I will manage these emails manually
     #### B. EmailsToKeepForAtLeast30Days.txt is for emails that I want to keep based on the delete condition
     ####            The delete condition is set to the variable End30
     #### I will append these two text files as needed
     ####
     #### Email maintenance conditions
     #### 1. Delete emails that have no email address
     #### 2. Keep emails that are in the EmailsToKeep.txt text file
     #### 3. Keep emails that are in the EmailsToKeepForAtLeast30Days.txt text file
     ####    A. Keep emails that are newer and equal to the value of variable End30
     ####    B. Delete the emails that are older than the value of variable End30
     #### 4. Delete emails that were not included in any of the EmailsToKeep.txt or EmailsToKeepForAtLeast30Days.txt text files
     ## ---------------------------------------------------------------------------
     import win32com.client, datetime, string, time
     from datetime import datetime, date, timedelta
    
     ############################################################################################
     ############ Adding date to end of file name
     start_c = datetime.now(); ##print start_c
     c1 = (("%(start_c)s" % vars()).partition(' ')[0]); ##print c1
     new_str = string.replace(c1, '-', '_');new_str = "_"+new_str; ##print(new_str)
    
     #### Path
     path = "S:\PythonProjects\EmailProject"
     Bslash = "\\"
    
     #### Text file extension
     extt = ".txt"
    
     #### Existing text file of emails to keep
     EmailKTF = "EmailsToKeep"
     EmailKTFTextFile = ("%(path)s%(Bslash)s%(EmailKTF)s%(extt)s" % vars()); ##print EmailKTFTextFile
    
     #### Existing text file of emails used to delete specific emails after meeting delete condition
     TextFile30Day = "EmailsToKeepForAtLeast30Days"
     EmailTextFile30Day = ("%(path)s%(Bslash)s%(TextFile30Day)s%(extt)s" % vars()); ##print EmailTextFile30Day
    
     #### The delete text file
     EmailT = "EmailsDeletedTextFile"
     EmailTextFile = ("%(path)s%(Bslash)s%(EmailT)s%(new_str)s%(extt)s" % vars()); ##print EmailTextFile
    
     ############################################################################################
     ############ Create delete text file if it does not exist or truncate if it does exist
     WriteEmailTextFile2=open('%(EmailTextFile)s' % vars(),'w')
     WriteEmailTextFile2.close()
    
     #### Opening delete text files to write deleted emails
     WriteEmailTextFile=open('%(EmailTextFile)s' % vars(),'a')
    
     ############ The delete condition below
     ############ Creating the date that will determine which emails will be deleted
     cur_date = datetime.today()
    
     #### Days to keep
     Dy = 21
     datedays = cur_date-timedelta(days=Dy)
     EndDy = "{}".format(datedays.strftime("%m/%d/%Y 00:00:00"))
     EndDy = '"' + EndDy + '"'; ##print End30
    
     #### Counters
     TotalEmailsRead = 0
     TotalEmailInRead = 0
     TotalEmailsDeleted = 0
    
     #### Setting email
     outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
     inbox = outlook.GetDefaultFolder(6)
     messages = inbox.Items
     messages.Sort("[ReceivedTime]", True)
     m = messages.GetFirst()
    
     #### Loop for emails     
     for m in list(messages):
         TotalEmailsRead += 1
    
         EmailDate = m.ReceivedTime; ##print EmailDate
         EmailDate = datetime.strptime(str(EmailDate), '%m/%d/%y %H:%M:%S'); ##print EmailDate
         EmailDate = EmailDate.strftime('%m/%d/%Y %H:%M:%S'); ##print EmailDate
         EmailDate = '"' + EmailDate + '"'; ##print EmailDate;print End30
    
         sender = m.SenderEmailAddress
         sender = sender.lower()
    
     ##    if sender == "[email protected]" and EmailDate < End30:
     ##        print ("\n      AAAAAAA - Email = %(sender)s - Email Date = %(EmailDate)s - %(End30)s is the Cut off date" % vars())
     ##    print ("\n      BBBBBBB - %(EmailDate)s - %(End30)s - %(sender)s" % vars())
    
         KTF = open('%(EmailKTFTextFile)s' % vars(), 'r')
         TF30 = open('%(EmailTextFile30Day)s' % vars(), 'r')
         if sender == "":
             TotalEmailInRead += 1
     ##        print ("\n    1111  Deleted - Email sender is blank" % vars())
             line = ("No Sender : %(EmailDate)s\n" % vars())
             WriteEmailTextFile.write(line)
             m.Delete()
             TotalEmailsDeleted += 1
             time.sleep(.25)
         elif sender in KTF.read():
             TotalEmailInRead += 1
     ##        print ("\n2222 %(sender)s : %(EmailDate)s - IS IN %(EmailKTF)s text file" % vars())
             time.sleep(.25)
         elif sender in TF30.read():
             TotalEmailInRead += 1
     ##        print ("\n3333 %(sender)s : %(EmailDate)s - IS IN %(TextFile30Day)s text file" % vars())
             if EmailDate < EndDy:
     ##            print ("\n    4444 Deleted - %(sender)s : %(EmailDate)s : %(EndDy)s - IS IN %(TextFile30Day)s text file" % vars())
                 line = ("%(sender)s : %(EmailDate)s : %(EndDy)s - IS IN email 30 day text file\n" % vars())
                 WriteEmailTextFile.write(line)
                 m.Delete()
                 TotalEmailsDeleted += 1
                 time.sleep(.25)
         else:
             TotalEmailInRead += 1
     ##        print ("\n    5555  Deleted - %(sender)s : %(EmailDate)s - IS NOT IN the %(EmailKTF)s and %(TextFile30Day)s text files" % vars())
             line = ("%(sender)s : %(EmailDate)s - IS NOT IN any of the read email text files\n" % vars())
             WriteEmailTextFile.write(line)
             m.Delete()
             TotalEmailsDeleted += 1
             time.sleep(.25)
         KTF.close()
         TF30.close()
    
     WriteEmailTextFile.close()
    
     print 'This is the total number of emails read from Outlook Inbox = ' + str(TotalEmailsRead)
     print 'This is the total number of emails processed in if statements = ' + str(TotalEmailInRead)
     print 'This is the total number of emails deleted in if statements = ' + str(TotalEmailsDeleted)
    
日暮斜阳 2024-09-15 13:49:24

尝试使用 https://github.com/ikvk/imap_tools

from imap_tools import MailBox 

# DELETE all messages from INBOX
with MailBox('imap.mail.com').login('[email protected]', 'password', 'INBOX') as mailbox:
    mailbox.delete(mailbox.uids('ALL'))

Try to use https://github.com/ikvk/imap_tools

from imap_tools import MailBox 

# DELETE all messages from INBOX
with MailBox('imap.mail.com').login('[email protected]', 'password', 'INBOX') as mailbox:
    mailbox.delete(mailbox.uids('ALL'))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文