Ejemplo n.º 1
0
def incoming(request):
    """
    Accept a new email message directly via the AppEngine email facility. The
    entire email message is contained in the POST body of *email*.
    
    :param HttpRequest request: A web request.
    :rtype: An HttpResponse object.
    """
    logging.info('Incoming email received.')
    
    try:
        msg = InboundEmailMessage(request.raw_post_data)
        
        usetting = UserSetting.gql('WHERE email = :1', msg.sender)
        if usetting.count() == 0:
            logging.warn('Received email from an unrecognized sender: ' + msg.sender)
            
            return render_to_response('msg_receipt.email', mimetype='text/plain')
            
        if not usetting.get().is_contrib:
            logging.warn('Received email from an unauthorized contributor: ' + msg.sender)
            
            return render_to_response('msg_receipt.email', mimetype='text/plain')
            
        content = ''
        for content_type, body in msg.bodies('text/plain'):
            headers = True
            date = False
            for line in str(body).split('\n'):
                if not date:
                    parts = line.split(' ')
                    line = ' '.join(parts[len(parts)-5:])
                    date = datetime.strptime(line, '%a %b %d %H:%M:%S %Y')
                    logging.debug(str(date))
                    
                if headers and line == '':
                    headers = False
                elif not headers:
                    content += '%s\n' % line
        
        if content == '':
            logging.warn('Received an email, but no text/plain bodies.')
        else:
            logging.info('Compiled plain-text email: body length=%d' % len(content))
            
            newtitle = msg.subject.replace('\n','').replace('\r','')
            content = content.lstrip('\t\n\r ')
            email = Email(title=newtitle, body=content, date=date, views=0, rating=0)
            email.put()
            
            logging.info('Processing new data for tokens & tags')
            
            _process_new(email)
            
    except Exception, ex:
        logging.error('Error processing new email. %s' % ex)
    def testReceiveBasic(self):
        mail = InboundEmailMessage(
            """From: =?ISO-2022-JP?B?GyRCJUYlOSVIGyhC?= <*****@*****.**>
To: =?ISO-2022-JP?B?GyRCJUYlOSVIGyhC?= <*****@*****.**>, [email protected], [email protected]
Subject: New Issue
X-Enigmail-Version: 1.1.1
Content-Type: text/plain; charset=ISO-2022-JP
Content-Transfer-Encoding: 7bit

Test
""")

        urlfetch.fetch = Mock()
        urllib.urlencode = Mock()

        mail_handler = MailHandler()

        mail_handler.request = Mock()
        mail_handler.request = Mock()
        mail_handler.request.url = 'http://localhost/_ah/mail/to%2ba_track%40test.com'

        mail_handler.receive(mail)

        urlfetch.fetch.assert_call_count(1)
        args, keywords = urlfetch.fetch.call_args
        ok_('url' in keywords)

        urllib.urlencode.assert_call_count(1)
        args, keywords = urllib.urlencode.call_args
        assert_equal(args[0]['issue[project]'], 'to')
        assert_equal(args[0]['issue[tracker]'], 'a_track')
Ejemplo n.º 3
0
  def get(self):
    if not users.is_current_user_admin():
      self.error(401)
      return

    # remove the old test
    name = "test_feed"
    feed = MailFeed.query(MailFeed.name == name).get()
    if feed:
      for item in MailFeedItem.query(ancestor=feed.key):
        item.key.delete()
      feed.key.delete()

    # now make some test stuff
    feed = MailFeed(name=name)
    feed.put()

    logging.info('added new feed: %s', name)

    testdata = os.path.join(os.path.dirname(__file__), 'testdata')
    etf = EmailToFeed()

    for x in range(1, 4):
      filename = os.path.join(testdata, "email-%02d.txt" % x)
      logging.info('adding: %s', filename)
      self.response.out.write(filename + '</br>')
      f = file(filename)
      body = '\r\n'.join(line.rstrip() for line in f)
      f.close()
      # now inject this into the code where we process emails.
      msg = InboundEmailMessage(body)
      etf.receive(msg, feed)
    self.response.out.write('<p><button onClick="history.back()">' +
                            'DONE</button></p>')
Ejemplo n.º 4
0
    def getFirstBatch(self):
        user = users.get_current_user()

        if user:
            message_array = []

            query = UserSubscription.query(
                UserSubscription.userId == user.user_id())
            for userSubscription in query.iter():
                key = ndb.Key(MailMessage, userSubscription.serviceId)
                mailQuery = MailMessage.query(
                    ancestor=key).order(-MailMessage.create_date)
                mails = mailQuery.fetch(limit=2)

                for mail in mails:
                    mime_message_text = mail.mime_message
                    mime_message = InboundEmailMessage(
                        mime_message=mime_message_text)

                    plaintext_bodies = mime_message.bodies('text/plain')
                    #html_bodies = mime_message.bodies('text/html')

                    for content_type, body in plaintext_bodies:
                        decoded_body = body.decode()
                    #for content_type, body in html_bodies:
                    #    decoded_body = body.decode()

                    text = decoded_body[:160]
                    if len(text) < len(decoded_body):
                        text += '...'

                    message_array.append({
                        'imageUrl':
                        'https://via.placeholder.com/60x60',
                        'title':
                        'message from ' + str(mail.create_date),
                        'text':
                        text,
                        'body':
                        decoded_body
                    })

            self.response.content_type = 'application/json'
            self.response.write(json.encode(message_array))
        else:
            self.error(403)
Ejemplo n.º 5
0
 def post(self):
     in_msg = InboundEmailMessage(self.request.body)
     logging.info('You\'ve got mail: "%s" %s' % (in_msg.subject, in_msg.date))
     body = in_msg.bodies().next()
     if body[0] != "text/html":
         logging.warn("HTML body not found")
     # Unescape because Gmail escapes HTML tags when forwarding
     body_decoded = HTMLParser().unescape(body[1].decode())
     msg = Email(
         parent=Email.ANCESTOR_KEY,
         subject=in_msg.subject,
         sender=in_msg.sender,
         to=in_msg.to,
         body_html=body_decoded,
         read=False,
     )
     msg.put()
     parse_email(msg)
Ejemplo n.º 6
0
    def test_expects_inbound_email_to_be_handled(self):
        # Arrange
        client = TestApp(app)
        mime_message = MIMEText('Hello world!')
        mime_message['Subject'] = 'Mailer Test'
        mime_message['From'] = '*****@*****.**'
        mime_message['To'] = '*****@*****.**'
        mail_message = InboundEmailMessage(mime_message)

        # Assume
        endpoint = '/_ah/mail/test.appspotmail.com'
        body = mail_message.original.as_string()

        # Act
        response = client.post(endpoint, body)

        # Assert
        self.assertEqual(response.status_code, 200, response)
Ejemplo n.º 7
0
def incoming(request):
    """
    Accept a new email message directly via the AppEngine email facility. The
    entire email message is contained in the POST body of *email*.
    
    :param HttpRequest request: A web request.
    :rtype: An HttpResponse object.
    """
    logging.info('Incoming email received.')

    try:
        msg = InboundEmailMessage(request.raw_post_data)

        usetting = UserSetting.gql('WHERE email = :1', msg.sender)
        if usetting.count() == 0:
            logging.warn('Received email from an unrecognized sender: ' +
                         msg.sender)

            return render_to_response('msg_receipt.email',
                                      mimetype='text/plain')

        if not usetting.get().is_contrib:
            logging.warn('Received email from an unauthorized contributor: ' +
                         msg.sender)

            return render_to_response('msg_receipt.email',
                                      mimetype='text/plain')

        content = ''
        for content_type, body in msg.bodies('text/plain'):
            headers = True
            date = False
            for line in str(body).split('\n'):
                if not date:
                    parts = line.split(' ')
                    line = ' '.join(parts[len(parts) - 5:])
                    date = datetime.strptime(line, '%a %b %d %H:%M:%S %Y')
                    logging.debug(str(date))

                if headers and line == '':
                    headers = False
                elif not headers:
                    content += '%s\n' % line

        if content == '':
            logging.warn('Received an email, but no text/plain bodies.')
        else:
            logging.info('Compiled plain-text email: body length=%d' %
                         len(content))

            newtitle = msg.subject.replace('\n', '').replace('\r', '')
            content = content.lstrip('\t\n\r ')
            email = Email(title=newtitle,
                          body=content,
                          date=date,
                          views=0,
                          rating=0)
            email.put()

            logging.info('Processing new data for tokens & tags')

            _process_new(email)

    except Exception, ex:
        logging.error('Error processing new email. %s' % ex)