简体   繁体   中英

How do you find the requested URL with Google App Engine's Python Mail service?

My Google App Engine app wants to store various incoming emails including who the email was addressed to. I am trying to figure out how to look at the URL the email was posted to so I can find the intended recipient.

app.yaml has:

inbound_services:
- mail
handlers:
- url: /_ah/mail/.+ 
  script: handle_incoming_email.py 
  login: admin

The Python script has:

class Message(db.Model):
    recipient = db.stringProperty()
    subject = db.stringProperty()
    # etc.

class MyMailHandler(InboundMailHandler):
    def receive(self, mail_message):
        msg = Message(subject=mail_message.subject, recipient=???)
        msg.put()

application = webapp.WSGIApplication([MyMailHandler.mapping()], debug=True)

So if an email is sent to john@myapp.appspot.com, the recipient would be john@myapp.appspot.com. If the email is sent to jane@myapp.appspot.com, the recipient would be jane@myapp.appspot.com, etc.

I know I could sift through the mail_message.to field, but I'd rather look at the actual incoming URL. Seems like it should be straightforward, but I can't figure it out.

该地址位于处理程序URL中,您可以查看self.request.path来检索它,但实际上应该使用mail_message获取此值。

OK, went to the source to figure out what receive() and mapping() do. I ended up doing what I wanted this way:

class MyEmailHandler(InboundMailHandler):
    def post(self,recipient):
        # 'recipient' is the captured group from the below webapp2 route
        mail_message = mail.InboundEmailMessage(self.request.body)
        # do stuff with mail_message based on who recipient is

app = webapp2.WSGIApplication(
    [(r'/_ah/mail/(.+)@.+\.appspotmail\.com',MyEmailHandler)],
    debug=True)

The webapp2 router allows capturing groups, which it sends as arguments to the handler. Here the captured group is the 'recipient' in recipient@myapp.appspotmail.com. But you can't use the mapping() convenience function (which doesn't do anything much in this case anyway) or the receive method in the handler (which really just gets the email message from the request and puts it in the args to receive.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM