Exemple #1
0
def post(request):
    """ Add in a post """
    log("Processing email message")
    mailobj = mail.InboundEmailMessage(request.raw_post_data)
    to = mailobj.to

    if to in settings.ALLOWED_RECEIVING_ADDRESSES:
        key = settings.ARECIBO_PUBLIC_ACCOUNT_NUMBER
    else:
        key = to.split("-", 1)[1].split("@")[0]
        if key != settings.ARECIBO_PUBLIC_ACCOUNT_NUMBER:
            log("To address (%s, to %s) does not match account number (%s)" %
                (key, to, settings.ARECIBO_PUBLIC_ACCOUNT_NUMBER))
            return

    for content_type, body in mailobj.bodies("text/plain"):
        if mailobj.subject.find(" Broken ") > -1:
            log("Trying to parse body using 404 parser")
            result = parse_404(body, mailobj.subject)
        else:
            log("Trying to parse body using 500 parser")
            result = parse_500(body, mailobj.subject)
        err = Error()
        result["account"] = key
        populate(err, result)

    return render_plain("message parsed")
Exemple #2
0
    def post(self, reply_to_id):
        incoming_mail = mail.InboundEmailMessage(self.request.body)
        model = email_models.FeedbackEmailReplyToIdModel.get_by_reply_to_id(
            reply_to_id)

        if model is None:
            raise self.PageNotFoundException

        user_id = model.user_id
        exploration_id = model.exploration_id
        thread_id = model.thread_id

        # Get text message from email.
        msg = list(
            incoming_mail.bodies(content_type='text/plain'))[0][1].decode()

        # Add new feedback message to thread.
        feedback_services.create_message(exploration_id,
                                         thread_id,
                                         user_id,
                                         None,
                                         None,
                                         msg,
                                         received_via_email=True)
        self.render_json({})
Exemple #3
0
 def post(self, *args, **kwargs):
     msg = mail.InboundEmailMessage(self.request.body)
     logging.info('Mail from: {}'.format(msg.sender))
     logging.info('Subject: {}'.format(msg.subject))
     for content_type, body in msg.bodies():
         logging.info(content_type)
         logging.info(body.decode())
Exemple #4
0
    def post(self):
        message = mail.InboundEmailMessage(self.request.body)
        ## Get the traderID from the post based on the email address and "forward" the email
        this_post = Post.query(
            Post.contact == message.to).order(-Post.engage).get()
        email_to = this_post.traderID

        if mail.is_email_valid(email_to):
            email_messages = message.bodies('text/plain')
            email = get_email_text("Post Reply")

            for content_type, msg in email_messages:
                full_message = mail.EmailMessage(
                    sender="%s <%s@%s>" %
                    (bitsettings.site_name, bitsettings.email_local,
                     bitsettings.email_suffix),
                    subject="%s %s - %s" %
                    (bitsettings.email_subject, this_post.title,
                     str(this_post.price)),
                    to="%s <%s>" % (email_to.split('@')[0], email_to),
                    reply_to=message.sender,
                    body=email.find('header').text + "\n\n" +
                    str(message.subject).upper() + "\n" + msg.decode() +
                    "\n\n" + email.find('footer').text,
                )
                full_message.send()
Exemple #5
0
    def setUp(self):
        super(FacebookEmailTest, self).setUp()
        self.fea = FacebookEmailAccount(
            id='212038',
            email_user='******',
            domain_urls=['http://foo.com/'],
            domains=['foo.com'],
        )
        self.fea.put()

        self.handler = EmailHandler()
        self.handler.request = webapp2.Request.blank(
            '/_ah/mail/[email protected]')
        self.handler.response = self.response

        headers = Message()
        headers['Message-ID'] = 'SMTP-123-xyz'
        self.mail = mail.InboundEmailMessage(
            sender='*****@*****.**',
            to='*****@*****.**',
            subject='Ryan Barrett commented on your post.',
            body='plain text is useless',
            html=COMMENT_EMAIL_USERNAME,
            mime_message=headers,
        )

        gr_facebook.now_fn = lambda: datetime(1999, 1, 1)
Exemple #6
0
    def post(self, reply_to_id):
        incoming_mail = mail.InboundEmailMessage(self.request.body)
        if feconf.ENABLE_GENERALIZED_FEEDBACK_THREADS:
            model = (email_models.GeneralFeedbackEmailReplyToIdModel.
                     get_by_reply_to_id(reply_to_id))
        else:
            model = email_models.FeedbackEmailReplyToIdModel.get_by_reply_to_id(
                reply_to_id)

        if model is None:
            raise self.PageNotFoundException

        user_id = model.user_id
        thread_id = model.thread_id

        # Get text message from email.
        msg = list(
            incoming_mail.bodies(content_type='text/plain'))[0][1].decode()

        # Add new feedback message to thread.
        feedback_services.create_message(thread_id,
                                         user_id,
                                         None,
                                         None,
                                         msg,
                                         received_via_email=True)
        self.render_json({})
Exemple #7
0
    def post(self, **kwargs):
        """Transforms body to email request.

        :param kwargs:
            Keyword arguments from the matched URL rule.
        """
        return self.receive(mail.InboundEmailMessage(self.request.data),
                            **kwargs)
Exemple #8
0
def emailToCard(request):
  if request.POST:
    message = mail.InboundEmailMessage(request.raw_post_data)
    logging.info("Email To Card from " + message.sender)
    (front, back, settings, fields) = parseEmail(message)
    if settings != None:
      createCardFromEmail(front, back, settings, fields)
  return HttpResponse('ok')
Exemple #9
0
  def update(self, to):
    message = mail.InboundEmailMessage(self.request.body)

    # Ensure that the message always has a subject
    if not hasattr(message, "subject"):
      message.subject = "<no subject>"

    # We want the plaintext version of the body (not the HTML formatted one)
    (_, encoded_body), = list(message.bodies("text/plain"))

    # Split the body into lines and keep all the lines until we see the first
    # "quoted" line (starting with >).
    lines = []

    for line in encoded_body.decode().split("\n"):
      if line.startswith(">"):
        break

      # Strip trailing whitespace and add to the list of lines.
      lines.append(line.rstrip())

    # Get rid of any trailing whitespace from the chunk of text.
    lines = "\n".join(lines).strip().split("\n")

    # If the last line contains noreply@dailymeeting, it's VERY likely a
    # 'reply', so remove it.
    if "*****@*****.**" in lines[-1]:
      lines = lines[:-2]

    # Put the lines back together to form the final body.
    body = "\n".join(lines).strip()

    # Log that the e-mail happened. The record will also exist in the mailbox
    # for [email protected].
    template = (u"Received inbound e-mail message:\n"
                u"From: {message.sender}\n"
                u"To: {message.to}\n"
                u"Subject: {message.subject}\n"
                u"Body:\n"
                u"=== Original ===\n"
                u"{original_body}\n"
                u"=== End Original ===\n"
                u"=== Trimmed ===\n"
                u"{body}\n"
                u"=== End Trimmed ===")

    logging.info(template.format(message=message, body=body,
                 original_body=encoded_body.decode()))

    if not body:
      logging.info("Body was empty, skipping note.")
      return

    email = message.sender

    if '<' in email and email.endswith('>'):
      email = email[:-1].split('<', 2)[1]
Exemple #10
0
    def __init__(self, body):
        # make email obj from body
        message = mail.InboundEmailMessage(body)

        # list of emails: ['*****@*****.**', ...]
        self.to = [a[1] for a in getaddresses([message.to])]
        self.cc = [a[1] for a in getaddresses([getattr(message, 'cc', '')])]

        self.recipient = None

        # check hook recipient in message.to list first
        for addr in self.to:
            if (addr.split('@')[1] == 'emailhooks.xyz'):
                self.recipient = addr.split('@')[0]
                break

        # if not in message.to, parse hook recipient from forwarding
        # details following the patterns:
        # "for <_____ @emailhooks.xyz>" or "for _____ @emailhooks.xyz"
        if (self.recipient is None):
            match = re.search('for <?(\S+)@emailhooks\.xyz', body,
                              re.IGNORECASE)
            self.recipient = match.group(1).lower() if match else None

        self.sender = parseaddr(message.sender)[1]
        self.subject = getattr(message, 'subject', '')
        self.date = message.date

        self.html_body = ''
        for _, body in message.bodies('text/html'):
            self.html_body = body.decode()

        self.plain_body = ''
        for _, plain in message.bodies('text/plain'):
            self.plain_body = plain.decode()

        # Attachments are a list of tuples: (filename, EncodedPayload)
        # EncodedPayloads are likely to be base64
        #
        # EncodedPayload:
        # https://cloud.google.com/appengine/docs/python/refdocs/google.appengine.api.mail#google.appengine.api.mail.EncodedPayload
        #
        self.attachments = []

        for attachment in getattr(message, 'attachments', []):
            encoding = attachment[1].encoding
            payload = attachment[1].payload

            if (not encoding or encoding.lower() != 'base64'):
                payload = attachment[1].decode().encode('base64')

            self.attachments.append({
                'filename': attachment[0],
                'payload': payload
            })
    def _assertGoogleDocIdExtraction(self, filename, expected_google_doc_ids):
        email_raw = None
        f = open("test_emails/%s" % filename, "r")
        with f:
            email_raw = f.read()

        inbound_msg = google_mail_api.InboundEmailMessage(email_raw)

        google_doc_ids = (mail.NewProjectsMailHandler.
                          google_doc_ids_from_message(inbound_msg))

        self.assertEquals(sorted(expected_google_doc_ids),
                          sorted(google_doc_ids))
Exemple #12
0
def email_to_feed(email):
    logger.info('Email: %s', email)
    account, _ = email.split('@', 1)
    logger.info('Account: %s', account)
    unique_key, feed_type, version = account.split('_')
    feed_type, version = map(int, (feed_type, version))
    logger.info('unique_key: %s feed_type:%s version:%s', unique_key, feed_type, version)
    feed = FEED_TYPE_TO_CLASS[feed_type].for_email(unique_key)
    logger.info('Found feed: %s', feed)
    mail_message = mail.InboundEmailMessage(request.stream.read())
    entry = yield feed.create_entry_from_mail(mail_message)
    yield publish_entry(entry, feed)

    raise ndb.Return(jsonify(status='ok'))
Exemple #13
0
 def post(self):
     message = mail.InboundEmailMessage(self.request.body)
     sender = message.sender
     url = message.subject
     try:
         result = urllib2.urlopen(url)
         page = result.read()
         out_message = mail.EmailMessage(
             sender=FROM, subject='RE: {}'.format(message.subject))
         out_message.to = message.sender
         out_message.body = page
         out_message.html = page
         out_message.send()
     except urllib2.URLError, e:
         logging.exception(e)
Exemple #14
0
  def post(self, name):
    """Transforms body to email request."""

    try:
      name = urllib.unquote(name).split('@')[0]
    except:
      pass

    # get the feed object
    feed = MailFeed.query(MailFeed.name == name).get()
    if feed is not None:
      self.receive(mail.InboundEmailMessage(self.request.body), feed)
    else:
      # 404 ?
      pass
Exemple #15
0
def post(request):
    """ Add in a post """
    log("Processing email message")
    mailobj = mail.InboundEmailMessage(request.raw_post_data)
    found = False

    for content_type, body in mailobj.bodies("text/plain"):
        found = parse(content_type, body)
    for content_type, body in mailobj.bodies("text/html"):
        found = parse(content_type, body)

    if not found:
        log("No contents found in the message.")

    return render_plain("message parsed")
Exemple #16
0
    def post(self):
        logging.info("Request headers:\n%s" %
                     "\n".join("- %s: %s" % h
                               for h in self.request.headers.iteritems()))
        body = self.request.body
        msg = mail.InboundEmailMessage(body)
        logging.debug("Received %.1fkB from '%s'" %
                      (len(body) / 1024., msg.sender))

        if msg.attachments:

            def attachment_info((filename, payload)):
                return "- '%s' (%.1fkB; %s)" \
                       % (filename,
                          len(payload.decode()) / 1024.,
                          mail._GetMimeType(filename))

            logging.debug("%d attachments:\n%s" %
                          (len(msg.attachments), "\n".join(
                              map(attachment_info, msg.attachments))))

        ts = datetime.utcfromtimestamp(
            email.utils.mktime_tz(email.utils.parsedate_tz(msg.date)))
        to = sorted({s.strip() for s in msg.to.split(",")})
        ent = Inmail(
            mail_timestamp=ts,
            sender=msg.sender,
            recipients=to,
            # the subject field is undefined if no subject
            subject=getattr(msg, 'subject', None),
            body=body)
        try:
            ent.put()
        except RequestTooLargeError:
            logging.exception("Failed to store Inmail")
            mail.send_mail(
                sender="info@%s.appspotmail.com" % get_application_id(),
                to=msg.sender,
                subject="Auto-reply: Too large email",
                body="Hello dear %s,\n\n"
                "An email you sent couldn't be received properly due to "
                "its excessive size (%.1fMB). Please retry with reduced "
                "attachments.\n\n"
                "Original email recipients: %s\n"
                "Subject: %s" % (msg.sender, len(body) / 1024.**2, msg.to,
                                 getattr(msg, 'subject', "(empty)")))
        else:
            logging.info("Stored email to %r" % ent.key)
Exemple #17
0
 def post(self):
     from email import header, utils
     message = mail.InboundEmailMessage(self.request.body)
     texts = message.bodies('text/plain')
     for text in texts:
         txtmsg = ""
         txtmsg = text[1].decode()
     url = txtmsg.encode('utf8')
     bm = Bookmarks()
     def txn():
         bm.original = url
         bm.title = header.decode_header(message.subject)[0][0]
         bm.comment = 'Sent via email'
         bm.user = users.User(utils.parseaddr(message.sender)[1])
         bm.put()
     ndb.transaction(txn)
     deferred.defer(main_parser, bm.key, _queue="parser")
Exemple #18
0
    def from_upload(cls, reader):
        """
        create from blobstore.BlobReader
        """
        message = mail.InboundEmailMessage(reader.read())

        item = cls()
        try:
            item.field_from = message.sender
            item.field_to = message.to
            item.field_subj = message.subject
            item.field_text = "".join([body.decode() for _ct, body in message.bodies('text/plain')])
            item.field_html = "".join([body.decode() for _ct, body in message.bodies('text/html')])
        except AttributeError:
            raise

        item.put()
        return item
    def post(self):

        inbound_message = mail.InboundEmailMessage(self.request.body)
        logging.info("Email request! Sent from %s with message subject %s" %
                     (inbound_message.sender, inbound_message.subject))

        body = inbound_message.subject
        logging.debug("email body arguments %s" % body)

        ## magic ##
        response = api_bridge.getarrivals(body, 10)

        # to make it a little easier to read, add newlines before each route report line
        response = response.replace('Route', '\nRoute')

        # send back the reply with the results
        header = "Thanks for your request! Here are your results...\n\n"
        footer = "\n\nThank you for using SMSMyBus!\nhttp://www.smsmybus.com"

        # setup the response email
        message = mail.EmailMessage()
        message.sender = config.EMAIL_SENDER_ADDRESS
        message.bcc = config.EMAIL_BCC_ADDRESS
        message.to = inbound_message.sender
        message.subject = 'Your Metro schedule estimates for stop %s' % getStopID(
            body)
        message.body = header + response + footer

        logging.debug('sending results to %s' % message.to)
        message.send()

        # create an event to log the event
        task = Task(url='/loggingtask',
                    params={
                        'phone': inbound_message.sender,
                        'inboundBody': body,
                        'sid': 'email',
                        'outboundBody': response,
                    })
        task.add('eventlogger')

        self.response.set_status(200)
        return
Exemple #20
0
    def post(self, reply_to_id):
        incoming_mail = mail.InboundEmailMessage(self.request.body)
        feedback_thread_reply_info = (
            email_services.get_feedback_thread_reply_info_by_reply_to_id(
                reply_to_id))

        if feedback_thread_reply_info is None:
            raise self.PageNotFoundException

        user_id = feedback_thread_reply_info.user_id
        thread_id = feedback_thread_reply_info.thread_id

        # Get text message from email.
        msg = list(
            incoming_mail.bodies(content_type='text/plain'))[0][1].decode()

        # Add new feedback message to thread.
        feedback_services.create_message(
            thread_id, user_id, None, None, msg, received_via_email=True)
        self.render_json({})
Exemple #21
0
    def receive(self, mail_message):
        logging.info("Email from "+ mail_message.sender)
        messageRecieved = mail.InboundEmailMessage(self.request.body);

        if(messageRecieved.to.lower() == "*****@*****.**"):
            sources = auth.lookupEmail(messageRecieved.sender);
            senderName = messageRecieved.sender;
            if(sources.count() != 0): 
                source = sources[0];
                senderName = source.firstName + " " + source.lastName
                
            html = ""
            for htmlpart in messageRecieved.bodies(content_type='text/html'):
                html = html + htmlpart[1].decode()
                
            attachments = None
            if(hasattr(messageRecieved, "attachments")):
                attachments = messageRecieved.attachments

            mailToUserGroup("public",senderName,"Message from " + senderName + ": " + messageRecieved.subject,messageRecieved.body, html, attachments)
Exemple #22
0
    def __init__(self, post_vars):
        """Constructs a new BounceNotification from an HTTP request.

    Properties:
      original: a dict describing the message that caused the bounce.
      notification: a dict describing the bounce itself.
      original_raw_message: the raw message that caused the bounce.

    The 'original' and 'notification' dicts contain the following keys:
      to, from, subject, text

    Args:
      post_vars: a dict-like object containing bounce information.
          This is typically the self.request.POST variable of a RequestHandler
          object. The following keys are expected in the dict:
            original-from
            original-to
            original-subject
            original-text
            notification-from
            notification-to
            notification-subject
            notification-text
            raw-message

    Raises:
      InvalidBounceNotification if any of the expected fields are missing.
    """
        try:
            self.__original = {}
            self.__notification = {}
            for field in ['to', 'from', 'subject', 'text']:
                self.__original[field] = post_vars['original-' + field]
                self.__notification[field] = post_vars['notification-' + field]

            self.__original_raw_message = mail.InboundEmailMessage(
                post_vars['raw-message'])
        except KeyError, e:
            raise InvalidBounceNotificationError(e[0])
Exemple #23
0
    def __init__(self, post_vars):
        """Constructs a new BounceNotification from an HTTP request.

    Properties:
      original: a dict describing the message that caused the bounce.
      notification: a dict describing the bounce itself.
      original_raw_message: the raw message that caused the bounce.

    The 'original' and 'notification' dicts contain the following keys:
      to, cc, bcc, from, subject, text

    Args:
      post_vars: a dict-like object containing bounce information.
          This is typically the self.request.POST variable of a RequestHandler
          object. The following keys are handled in the dict:
            original-from
            original-to
            original-cc
            original-bcc
            original-subject
            original-text
            notification-from
            notification-to
            notification-cc
            notification-bcc
            notification-subject
            notification-text
            raw-message
    """
        self.__original = {}
        self.__notification = {}
        for field in ['to', 'cc', 'bcc', 'from', 'subject', 'text']:
            self.__original[field] = post_vars.get('original-' + field, '')
            self.__notification[field] = post_vars.get('notification-' + field,
                                                       '')

        self.__original_raw_message = mail.InboundEmailMessage(
            post_vars.get('raw-message', ''))
Exemple #24
0
    def post(self):
        message = mail.InboundEmailMessage(
            self.request.body)  #Accept in bound mails

        new_email = model.EmailArchive()  #Set a new EmailArchieve entity
        new_email.from_ = message.sender
        new_email.subject = message.subject

        email_body = list(message.bodies(content_type='text'))[0]
        new_email.content = str(
            email_body[1])  #convert the message into readable string

        startIndex = 1 + new_email.from_.index('<')
        endIndex = new_email.from_.index('@')
        newString = new_email.from_[startIndex:endIndex]

        query = model.PlayerTag.query()

        for item in query:
            if (item.confirm == False and str(item.google_id) == newString
                    and new_email.subject.__contains__(item.activationToken)):
                item.confirm = True
                item.put()
                new_email.put()
Exemple #25
0
 def post(self):
     """Transforms body to email request."""
     self.receive(mail.InboundEmailMessage(self.request.body))
Exemple #26
0
    def post(self):
        # create email message and parse out fields
        message = mail.InboundEmailMessage(self.request.body)

        # list of emails: ['*****@*****.**', ...]
        to = [addr[1] for addr in getaddresses([message.to])]
        cc = [addr[1] for addr in getaddresses([getattr(message, 'cc', '')])]

        sender = parseaddr(message.sender)[1]
        subject = getattr(message, 'subject', '')
        date = message.date

        html_body = ''
        for _, body in message.bodies('text/html'):
            html_body = body.decode()

        plain_body = ''
        for _, plain in message.bodies('text/plain'):
            plain_body = plain.decode()

        # Attachements are a list of tuples: (filename, EncodedPayload)
        # EncodedPayloads are likely to be base64
        #
        # EncodedPayload:
        # https://cloud.google.com/appengine/docs/python/refdocs/google.appengine.api.mail#google.appengine.api.mail.EncodedPayload
        #
        attachments = []

        for attachment in getattr(message, 'attachments', []):
            encoding = attachment[1].encoding
            payload = attachment[1].payload

            if (not encoding or encoding.lower() != 'base64'):
                payload = attachment[1].decode().encode('base64')

            attachments.append({'filename': attachment[0], 'payload': payload})

        # logging, remove what you find to be excessive
        logging.info('From <%s> to [<%s>]', sender, '>, <'.join(to))
        logging.info('Subject: %s', subject)
        logging.info('Body: %s', plain_body)
        logging.info('Attachments: %s', [a['filename'] for a in attachments])

        # change to your endpoint (httpbin is cool for testing though)
        url = 'http://httpbin.org/post'

        payload = json.dumps({
            'sender': sender,
            'to': to,
            'cc': cc,
            'date': date,
            'subject': subject,
            'html_body': html_body,
            'plain_body': plain_body,
            'attachments': attachments
        })

        # add a key if you want to sign each request, or remove these lines
        key = 'XXXXXXXXXXXXXXXXXXXX'

        # hmac needs bytes (str() == bytes() in python 2.7)
        signature = hmac.new(bytes(key), bytes(payload),
                             hashlib.sha1).hexdigest()

        headers = {
            'Content-Type': 'application/json',
            'X-Email-Signature': signature,
        }

        # try to post to destination
        try:
            result = urlfetch.fetch(url=url,
                                    headers=headers,
                                    payload=payload,
                                    method=urlfetch.POST)

            logging.info('POST to %s returned: %s', url, result.status_code)
            logging.info('Response body: %s', result.content)
        except urlfetch.Error as err:
            logging.exception('urlfetch error posting to %s: %s', url, err)
Exemple #27
0
 def post(self, project_addr=None):
   logging.info('\n\n\nPOST for InboundEmail and project_addr is %r',
                project_addr)
   self.Handler(mail.InboundEmailMessage(self.request.body),
                urllib.unquote(project_addr))
Exemple #28
0
 def post(self, address):
   """Transforms body to email request."""
   self.receive(mail.InboundEmailMessage(self.request.data), address)
   return Response("OK")
Exemple #29
0
 def post(self):
     message = mail.InboundEmailMessage(self.request.body)
     logging.info('Got e-mail: %s', message)
Exemple #30
0
def _process_incoming_mail(raw_message, recipients, mailing_list):
    """Process an incoming email message."""
    recipients = [x[1] for x in email.utils.getaddresses([recipients])]

    incoming_msg = mail.InboundEmailMessage(raw_message)

    mailing_list_acronym = mailing_list.split('/')[3].split('@')[0]

    query = models.MailingList.all().filter('acronym =',
                                            mailing_list_acronym.lower())
    mailing_list = query.get()
    if mailing_list is None:
        # Create a new mailing-list
        newml = models.MailingList(name=mailing_list_acronym,
                                   acronym=mailing_list_acronym.lower())
        newml.put()
        mailing_list = newml

    logging.info("Received a message from: " + incoming_msg.sender + " TO: " +
                 str(recipients) + " for ML " + mailing_list_acronym)

    if 'X-Google-Appengine-App-Id' in incoming_msg.original:
        raise InvalidIncomingEmailError('Mail sent by App Engine')

    subject = incoming_msg.subject or ''
    sender = email.utils.parseaddr(incoming_msg.sender)[1]
    original = str(incoming_msg.original)

    body = None
    for content_type, payload in incoming_msg.bodies('text/plain'):
        body = payload.decode()
        break
    if body is None or not body.strip():
        raise InvalidIncomingEmailError('Ignoring empty message.')

    # We need to check if the header is internationalized
    try:
        decoded_subject = email.header.decode_header(subject)
        if decoded_subject[0][1]:
            subject = decoded_subject[0][0].decode(decoded_subject[0][1])
    except:
        logging.error('Unable to decode subject: %r', subject)

    # If the subject is long, this might come wrapped into more than one line.
    subject = ' '.join([x.strip() for x in subject.splitlines()])
    subject = subject.replace(mailing_list.clean_subject, '')
    query = models.MailingList.all()
    mailing_list = query.get()

    processed_subject = _process_string(subject)
    processed_body = _process_string(body)

    email_date = email.utils.parsedate_tz(incoming_msg.date)

    msg = models.Message(mailing_list=mailing_list,
                         subject=subject,
                         processed_body=processed_body,
                         processed_subject=processed_subject,
                         sender=db.Email(sender),
                         original=db.Text(original),
                         body=db.Text(body),
                         spam=False)
    if email_date:
        msg.created = datetime.datetime(*email_date[:6]) - datetime.timedelta(
            seconds=email_date[-1])

    # We now predict the type with Google Predict API
    credentials = StorageByKeyName(models.Credentials,
                                   "key_for_prediction_credentials",
                                   'credentials').get()
    logging.info('CREDENTIALS: ' + str(credentials))
    model = django_settings.GOOGLE_PREDICTION_MODEL
    if credentials:
        # Make the Google Prediction API call
        query = '"' + processed_subject + ' ' + processed_body + '"'
        [prediction,
         scores] = google_prediction.Predict(credentials, model, query)
        msg.prediction = prediction
        msg.scores = scores
    msg.put()

    user_address = '*****@*****.**'
    chat_message_sent = False
    msg = "Message '%s' from: %s\nPrediction: %s\n%s" % (
        msg.key().id(), incoming_msg.sender, msg.prediction, msg.subject)
    status_code = xmpp.send_message(user_address, msg)
    chat_message_sent = (status_code == xmpp.NO_ERROR)

    if not chat_message_sent:
        logging.error("Unable to send XMPP message: %s" % msg)