Deleting Messages from Server

Deleting Messages

The ImapClient class can delete messages from an IMAP server. The ImapClient class DeleteMessage() function is used to delete messages. It takes the message sequence number or unique ID as a parameter. The ImapClient provides DeleteMessage and DeleteMessages methods for deleting messages one by one or multiple. The following code snippet shows you how to delete an email message with the message ID 1 from an IMAP server.

For complete examples and data files, please go to https://github.com/aspose-email/aspose-email-python-dotnet
with ImapClient("imap.gmail.com", 993, "username", "password") as client:
client.select_folder("Inbox")
message = MailMessage("from@Aspose.com", "to@Aspose.com", "Message deletion using IMAP Client", "EMAILNET-35227 Add ability in ImapClient to delete message")
messageInfoCol = client.list_messages()
print("Total messages in Inbox before appending: " + str(len(messageInfoCol)))
emailId = client.append_message(message)
print("Email appended to inbox with email Id: " + emailId)
# Now verify that all the messages have been appended to the mailbox
messageInfoCol = client.list_messages()
print("Total messages in Inbox after appending: " + str(len(messageInfoCol)))
client.delete_message(emailId)
client.commit_deletes()
messageInfoCol = client.list_messages()
print("Total messages in Inbox after deletion: " + str(len(messageInfoCol)))

Deleting Multiple Messages

Multiple emails can be deleted from mailbox using the ImapClient of Aspose.Email API. The DeleteMessages method provides a number of options to delete multiple messages from the server using unique ids, sequence numbers or ImapMessageInfoCollection elements. The following code snippet shows you how to delete multiple messages.

For complete examples and data files, please go to https://github.com/aspose-email/aspose-email-python-dotnet
with ImapClient("imap.gmail.com", 993, "username", "password") as client:
print(client.uid_plus_supported)
#Append some test messages
client.select_folder("Inbox")
uidList = []
messageInfoCol = client.list_messages()
print("Total messages in Inbox before appending: " + str(len(messageInfoCol)))
#No. of messages to be appended
messageNumber = 2
message = MailMessage("from@Aspose.com", "to@Aspose.com", "Message 1", "Add ability in ImapClient to delete message")
emailId = client.append_message(message)
uidList.append(emailId)
message = MailMessage("from@Aspose.com", "to@Aspose.com", "Message 2", "Add ability in ImapClient to delete message")
emailId = client.append_message(message)
uidList.append(emailId)
#Now verify that all the messages have been appended to the mailbox
messageInfoCol = client.list_messages()
print("Total messages in Inbox after appending: " + str(len(messageInfoCol)))
client.delete_messages(uidList, True)
client.commit_deletes()
messageInfoCol = client.list_messages()
print("Total messages in Inbox after deletion: " + str(len(messageInfoCol)))