added check for IMAP message deleted flag, move imap_expunge() and imap_close() out of the foreach loop