Recently,i have to develop a mail client for my work need,then i spend a few days reading documents and writing codes, and now i want to write some thing down just for memory.
There are two popular protocol of receiving email,IMAP and POP3,i choose imap because it has more feather.(RFC3501) Actually, because python gives us some powerful libraries, we need no effort to write code of fetching mails from our mailbox. But if you want to build some thing that work well, you have to know imap protocol well, there are lots of problem to handle.
Imap will give a Unique Identifier and Sequence Number to a message, they have some important feathers. First, Unique Identifier is consistant unless UIDVALIDATE changes, and we may not change all the time; Second, Sequence Number is unique in one mailbox, but not unique in mail server, so message of number 100 in
INBOX is different with message of number 100 in
SENT MAILS; Third, Unique Identifier is not grantied to be increased, although most of times it is.
Message has some flags to represent its feathers,such as:
\Seen : Message has been read \Answered : Message has been answered \Flagged : Message is "flagged" for urgent/special attention \Deleted : Message is "deleted" for removal by later EXPUNGE \Draft : Message has not completed composition (marked as a draft). \Recent : Message is "recently" arrived in this mailbox.
There are many Command in Imap, but we just need a few of them to achive our goal:
SELECT means to select a mailbox, then our command following is to handle messages in this mailbox, in fact, we cannot do
FETCH before we select a mailbox.
SEARCH means to search messages in mailbox, you can specify your own search command like
SINCE <date> and so on, it returns Sequence Number list that match your codition.
FETCH is to get message content by Sequence Number, your can decide to get specific parts by your own, like
RFC822.HEADER…… maybe you notice that we use Sequence Number to identify a message above, because Sequence Number is unique in a mailbox in one session, in fact, you can also use Unique Identifier, which is recommened by me.
SMTP is absolutely a important protocol in writing a mail client, but for this project, i just need a simple tool to send plain text message, so it’s too simple to write some trivial there. the whole project has upload to github, so you can check it here