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,
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.
Second - I edit the text or CSV file to create two text files.
Third - I write a second python program to delete or keep emails based on four conditions.
Delete emails that have no email address.
Keep emails that are in the EmailsToKeep.txt text file.
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.
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 == "alert@indeed.com" 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)