ksaylor11 ksaylor11 - 8 months ago 39
Python Question

how to set imap flags using Twisted

How do you delete messages using imap4.IMAP4Client? I cannot get the "deleted" tag correctly applied for using the "expunge" method.

I keep getting the following error:

Failure: twisted.mail.imap4.IMAP4Exception: Invalid system flag \

Sample code would be appreciated. This is what I have so far:

from twisted.internet import protocol, reactor
from twisted.mail import imap4

#Variables for connection
username = 'user@host.com'
password = 'mypassword'
host = 'imap.host.com'
port = 143

class IMAP4LocalClient(imap4.IMAP4Client):
def connectionMade(self):
self.login(username,password).addCallbacks(self._getMessages, self._ebLogin)

#reports any connection errors
def connectionLost(self,reason):

#drops the connection
def _ebLogin(self,result):
print result

def _programUtility(self,result):
print result
return self.logout()

def _cbExpungeMessage(self,result):
return self.expunge().addCallback(self._programUtility)

def _cbDeleteMessage(self,result):
return self.setFlags("1:5",flags=r"\\Deleted",uid=False).addCallback(self._cbExpungeMessage)

#gets the mailbox list
def _getMessages(self,result):
return self.list("","*").addCallback(self._cbPickMailbox)

#selects the inbox desired
def _cbPickMailbox(self,result):
return self.select(mbox).addCallback(self._cbExamineMbox)

def _cbExamineMbox(self,result):
return self.fetchMessage("1:*",uid=False).addCallback(self._cbDeleteMessage)

class IMAP4ClientFactory(protocol.ClientFactory):
def buildProtocol(self,addr):
return IMAP4LocalClient()

def clientConnectionFailed(self,connector,reason):
print reason


Changed to:

def _cbDeleteMessage(self,result):
return self.setFlags("1:5",flags=['\\Deleted'],uid=False).addCallback(self._cbExpungeMessage)

thanks to Jean-Paul Calderone and it worked, setFlags requires a list, not just a string.


I think there are two problems here.

First, you're passing a string as the flags parameter to setFlags. Notice the documentation for that parameter: The flags to set (type: Any iterable of str). Try a list containing one string, instead.

Second, \\Deleted is probably not a flag the server you're interacting with supports. The standard deleted flag in IMAP4 is \Deleted.