使用Google App Engine从电子邮件中收集数据

时间:2011-05-12 13:17:49

标签: google-app-engine parsing email

我是谷歌应用引擎(和python)的新手我正在实现一个系统,它将基本解析传入的电子邮件并将细节存储在数据存储中。现在我确实有它工作,但我觉得应该有一个更好的方法去做我现在的。

基本上,进入系统的电子邮件总是如下所示:

Order Details: Random Batch Name here

Order Status: 74 of 131 Shipped In Total

Message ID: 123456

Message Date: 21/04/2011 16:13:00

Mobile Number: 01234567890

Message: message would be here

我用来解析它的代码如下所示:

class LogSenderHandler(InboundMailHandler):
    def receive(self, message):

        # Get the body text from the e-mail
        plaintext_bodies = message.bodies('text/plain')
        for content_type, body in plaintext_bodies:
            body_text = body.decode().split('\n')

            # Loop through each line in the e-mail and discard a line if it is blank
            for line in body_text:
                if line != "":

                    # I'm sure there's a better way of doing this, just don't know how right now!
                    # Split the current line based on the ": " value and only let it be done once
                    splitline = line.split(': ', 1)

                    # Check to see which line we now have the details for and place value into the correct variable
                    if splitline[0] == "Order Details":
                        batch = splitline[1]
                    if splitline[0] == "Message ID":
                        messageID = splitline[1]
                    if splitline[0] == "Message Date":
                        messageDate = splitline[1]
                    if splitline[0] == "Mobile Number":
                        mobileNumber = splitline[1]
                    if splitline[0] == "Message":
                        theMessage = splitline[1]


        newNumber = SMSNumber( status = "Waiting",
                               batch = common.slugify(batch),
                               messageID = messageID,
                               messageDate = messageDate,
                               sentMessage = theMessage )

        newNumber._key_name = mobileNumber
        newNumber.put()

有没有更好的方法来解决这个问题?如果有人有任何意见,我将非常感激! :)

此致

1 个答案:

答案 0 :(得分:0)

更简洁的方法是迭代文件的行,分割冒号,并将行添加到Map。然后,从地图中读出相关条目并将它们传递给构造函数 - 如果它不存在则指定默认值。