0

Trying to extract just the email address from this format:

John Smith <[email protected]>

I have tried both of the following and it results in the same error:

IndexError: list index out of range

email_address = re.findall('(?<=\<)\w+@[a-zA-Z]+\.[a-z]+(?=\>)', sender)[0]

email_address = re.findall('<([^>])>', sender)[0]

Rest of code:

import webapp2
import logging
from google.appengine.ext.webapp import mail_handlers
from google.appengine.api import mail
import os
from main import WorkRequest
import re


class IncomingMailHandler(mail_handlers.InboundMailHandler):
    def receive(self, message):
        (encoding, payload) = list(message.bodies(content_type='text/plain'))[0]
        body_text = payload.decode()
        logging.info('Received email message from %s, subject "%s": %s' %
                     (message.sender, message.subject, body_text))

        logging.info (message.sender)
        logging.info(message.subject)
        logging.info(body_text)


        sender = str(message.sender)

        email_address = re.findall('<([^>])>', sender)[0]

        wr = WorkRequest()

        wr.email = email_address
        wr.userId = None
        wr.title = message.subject
        wr.content = body_text
        wr.status = "OPEN"
        wr.submission_type = "EMAIL"
        wr.assigned_to = "UNASSIGNED"
        wr.put()

application = webapp2.WSGIApplication([('/_ah/mail/.+', IncomingMailHandler)],debug=True)

Can anyone please help? I am using Google App Engine with Python if that matters.

3
  • 3
    can you do print(sender) and add the output to your question? Commented Dec 22, 2017 at 22:18
  • the regex looks good, it gets [email protected] out of "John Smith <[email protected]>" Commented Dec 22, 2017 at 22:19
  • 1
    The first regex works for me (assuming sender is John Smith <[email protected]>). The second one works if you add a plus sign after the closing square bracket. Commented Dec 22, 2017 at 22:21

1 Answer 1

1

In my case first regex works fine:

>>> sender = 'John Smith <[email protected]>'
>>> email_address = re.findall('(?<=\<)\w+@[a-zA-Z]+\.[a-z]+(?=\>)', 
        sender)[0]
>>> email_address
'[email protected]'

Second is invalid because you get empty list as a result, so you can't get item at index 0:

email_address = re.findall('<([^>])>', sender)
>>> email_address
[]

You can check your regex at http://rubular.com/ It's free and easy to use.

invalid

valid

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.