Search code examples
pythonemailwebweb-applicationsimap

Trying to make a Python code to print E-mail onto a website with IMAP, localhost doesn't respond


So I've been trying to make a code to print my Gmail inbox onto a website. I want to further develop this to only contain certain data from the email and write it onto a database. However, it does not seem to me that there is anything wrong with the code, but the localhost:8080 (The port I'm using) does not load at all. The browser has the loading icon when trying to access the page, but it does not load, even after hours. Command line does not respond with any errors. I also have the GMAIL imap settings correctly, and I have tried it with Outlooks email as well. Here is the code:

import webapp2
import smtplib
import time
import imaplib
import email


class ReadMail(webapp2.RequestHandler):

def get(self):
    mail = imaplib.IMAP4('xxx@gmail.com',993)

    mail.login('email@gmail.com','password')

    type, data = mail.search(None, 'ALL')
    mail_ids = data[0]

    id_list = mail_ids.split()   
    first_email_id = int(id_list[0])
    latest_email_id = int(id_list[-1])

    for i in range(latest_email_id,first_email_id, -1):
        typ, data = mail.fetch(i, '(RFC822)' )

        for response_part in data:
            if isinstance(response_part, tuple):
                msg = email.message_from_string(response_part[1])
                email_subject = msg['subject']
                email_from = msg['from']
                self.response.headers["Content-Type"] = "text/plain"
                self.response.write("From:" + email_from)
                self.response.write("Subject:" + email_subject)


routes = [('/', ReadMail),]

app = webapp2.WSGIApplication(routes, debug=True)

App.yml is correctly setup as well. This code works with something really simple, such as only containing a print "this". Hopefully someone can help with my problem, thanks in advance!


Solution

  • So after a while I got it working by making my own WSGI application file instead of using the webapp2. There are still some issues such as the message being formatted wrong, but this is my code now:

    from pyramid.config import Configurator
    from pyramid.response import Response
    import email, getpass, imaplib, os, re
    import sys
    detach_dir = "C:\OTHERS\CS\PYTHONPROJECTS"
    
    def imaptest(request):
    
        m = imaplib.IMAP4_SSL("imap.gmail.com")
        m.login("testi.protokolla@gmail.com", "testiprotokolla221")
    
        m.select("INBOX")
    
        resp, items = m.search(None, '(FROM "vallu.toivonen96@gmail.com")')
        items = items [0].split()
    
        my_msg = []
        msg_cnt = 0
        break_ = False
    
        for emailid in items[::1]:
            resp, data = m.fetch(emailid, "(RFC822)")
    
            if ( break_ ):
                break
    
            for response_part in data:
    
                if isinstance(response_part, tuple):
                    msg = email.message_from_string(response_part[1])
                    varSubject = msg['subject']
                    varDate = msg['date']
    
                    if varSubject[0] == '$':
                        r, d = m.fetch(emailid, "(UID BODY[TEXT])")
                        ymd = email.utils.parsedate(varDate)[0:3]
                        my_msg.append([ email.message_from_string(d[0][1]), ymd])
    
                        msg_cnt += 1
    
        # Print as HTML
        return Response(  
            'Content-Type': 'text/html'    
            "Your latest Email:" + str(msg)
        )
    
    config = Configurator()
    config.add_route('imaptest', '/imaptest')
    config.add_view(imaptest, route_name='imaptest')
    app = config.make_wsgi_app()