当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Maildir - open latest email and reply to sender

问题描述:

I've configured postfix on the email server with .forward file which saves a copy of email and invokes a python script. These emails are stored in Maildir format.

I want to use this python script to send a reply to the sender acknowledging that the email has been received. I was wondering if there is any way I can open/access that e-mail, get the header info and sender address and send email back.

I looked at several examples of Maildir functions of python, but they mostly add/delete e-mails. How can I open the latest e-mail received in Maildir/new and get the required information?

Thanks in advance. Apologies for the dumb question, but I am new to Python.

EDIT:

md = mailbox.Maildir('/home/abcd/Maildir')

message = md.iterkeys().next()

#print message

#for msg in md:

# subject = msg.get('Subject',"")

# print subject

print message

sender = message.get('From',"")

print sender

When I execute this, I do get the sender name.. but It is rather the oldest email arrived in Maildir/new folder not the latest one.

Also, if I use get_date function, what if two (or more) e-mails arrive on the same day?

网友答案:

Some hints for this:

  • You can open a Maildir with the mailbox.Maildir class (see the Documentation for mailbox)
  • You can iterate over all the mails in a Maildir via the method itervalues
  • Now you get all the mails in the Maildir. One of them is the most recent one.
  • The mails are objects of the class MaildirMessage, which is a subclass of Message. For these classes, also a documentation exists (on the same page as mailbox, currently)
  • With the method "get_date" on those objects, you can find out, which one is the most recent one. You still have to select it yourself.

So much as beginners help: A little bit you should also do by yourself.

You should make yourself familiar with the Python documentation - I agree, that it is not easy to find the right packages and how to use them, but you can try them directly in the Python shell.

Ok, here another code snippet:

newest = None
for message in md.itervalues():
   if newest == None or message.get_date() > newest.get_date():
      newest = message
# now newest should contain the newest message

Did not see your last question: get_date does not only contain the date, but also the time, because it gives the number of seconds since (normally) 1970.

分享给朋友:
您可能感兴趣的文章:
随机阅读: