Exemple #1
0
def update(request):
    # Get username and password and other credentials from posted data and updated into the db
    if request.method == 'POST':
        name = request.POST.get('name')
        code=  str(request.POST.get('countryCode'))
        mobile_no =code+ str(request.POST.get('mobile_no'))
        ldap_email = request.POST.get('ldap_email')
        ldap_pass = request.POST.get('ldap_pass')
        cse_email = request.POST.get('cse_email')
        cse_email_pass = request.POST.get('cse_email_pass')
        moodle_id = request.POST.get('moodle_id')
        moodle_pass = request.POST.get('moodle_pass')

        try:
            usr = Users(str(mobile_no))
            user = users.objects.get(pk=str(mobile_no))
            user_data = usr.getAll()

            if str(name) != "":
                user_data["name"] = name

            if str(ldap_email) != "":
                user_data["ldap_email"] = ldap_email

            if str(ldap_pass) != "":
                ldap_pass = str(encrypt_message(ldap_pass))
                user_data["ldap_pass"] = ldap_pass

            if str(cse_email) != "":
                user_data["cse_email"] = cse_email

            if str(cse_email_pass) != "":
                cse_email_pass = str(encrypt_message(cse_email_pass))
                user_data["cse_email_pass"] = cse_email_pass

            if str(moodle_id) != "":
                user_data["moodle_id"] = moodle_id

            if str(moodle_pass) != "":
                moodle_pass = str(encrypt_message(moodle_pass))
                user_data["moodle_pass"] = moodle_pass

            user_serializer = usersSerializer(user, data=user_data)
            if user_serializer.is_valid():
                user_serializer.save()
                #return JsonResponse({'message': 'User has been updated successfully!'}, status=status.HTTP_201_CREATED,safe=False)
                return render(request, 'timer.html', {'message': {'k1':'User has been updated successfully!\n ',
                'k2':'Please send \"join friend-identity\" (without quotes) to "+1 415 523-8886" to register to the whatsapp bot service. Then you can use the whatsapp bot as per your need.'}})
            else:
                #return JsonResponse(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST, safe=False)
                return render(request, 'timer.html', {'message': {'k1':'HTTP_400_BAD_REQUEST: Please Try again!','k2':''}})
        except users.DoesNotExist:
            #return JsonResponse({'message': 'The user does not exist'}, status=status.HTTP_404_NOT_FOUND, safe=False)
            return render(request, 'timer.html', {'message': {'k1':'The user does not exist','k2':''}})
Exemple #2
0
    def show_quizzes(self, sender_whatsapp_no, course_id):
        '''
        Show quizzes of a course
        Input:
            course_id (int) : ID of the course
        '''
        token, userid = Users(sender_whatsapp_no).getMoodle()
        if token == -1:
            return "Please register moodle credentials"

        print("userid:", token, userid)
        if token is None:
            return "Please update Moodle Credentials"

        try:
            payload = {'wstoken': token, 'wsfunction': 'mod_quiz_get_quizzes_by_courses', 'courseids[0]': course_id}

            res = requests.post('https://moodle.iitb.ac.in/webservice/rest/server.php?moodlewsrestformat=json',data=payload)
            i = 1
            table = list()
            for x in json.loads(res.text)['quizzes']:
                table.append([i, x['id'], x['name'], x['grade'], datetime.fromtimestamp(x['timeopen']), datetime.fromtimestamp(x['timeclose'])])
                table.append([])
                i += 1

            return (tabulate(table, headers = ['sl No', 'id', 'Name', 'Total Score', 'Quiz Opens', 'Quiz Closes']))
        except:
            pass
Exemple #3
0
    def show_courses(self, sender_whatsapp_no):
        '''
        Show details of all enrolled courses
        '''
        token, userid = Users(sender_whatsapp_no).getMoodle()
        if token == -1:
            return "Please register moodle credentials"

        print("userid:", token, userid)
        if token is None:
            return "Please update Moodle Credentials"

        url = 'https://moodle.iitb.ac.in/webservice/rest/server.php?moodlewsrestformat=json'

        payload = {
            'wstoken': token,
            'wsfunction': 'core_enrol_get_users_courses',
            'userid': userid
        }
        res = requests.post(url, data=payload)
        table = list()
        i = 1
        for x in json.loads(res.text):
            table.append(
                [i, x['id'], x['progress'], x['shortname'], x['fullname']])
            i += 1

        return (tabulate(table,
                         headers=[
                             'sl No', 'Course id', 'Progress', 'Short Name',
                             'Full Name'
                         ]))
Exemple #4
0
    def show_assignments(self, course, sender_whatsapp_no, show_only_due):
        '''
        Show assignments of a course
        Input:
            course (string) : filter for course name
            show_only_due (boolean) : when set to True, shows only due assignments
        '''
        course = course.lower()
        token, userid = Users(sender_whatsapp_no).getMoodle()
        if token == -1:
            return "Please register moodle credentials"

        print("userid:", token, userid)
        if token is None:
            return "Please update Moodle Credentials"

        payload = {
            'wstoken': token,
            'wsfunction': 'mod_assign_get_assignments'
        }

        res = requests.post(
            'https://moodle.iitb.ac.in/webservice/rest/server.php?moodlewsrestformat=json',
            data=payload)

        table = list()

        for x in json.loads(res.text)['courses']:
            i = 1
            if course in x['shortname'].lower(
            ) or course in x['fullname'].lower():
                for assignment in x['assignments']:
                    # assignment is not due
                    if show_only_due and datetime.fromtimestamp(
                            assignment['duedate']) < datetime.fromtimestamp(
                                time.time()):
                        continue

                    table.append([
                        i, x['shortname'], assignment['name'],
                        datetime.fromtimestamp(assignment['duedate'])
                    ])
                    table.append([])
                    i += 1

                table.append([])
                break
        if i > 1:
            return (tabulate(
                table,
                headers=['sl No', 'Course Name', 'Assignment', 'Due Date']))
        else:
            return "No assignments"
Exemple #5
0
    def show_all_due_assignments(self, sender_whatsapp_no):
        '''
        Show due assignments of all courses
        '''
        token, userid = Users(sender_whatsapp_no).getMoodle()
        if token == -1:
            return "Please register moodle credentials"

        print("userid:", token, userid)
        if token is None:
            return "Please update Moodle Credentials"

        payload = {
            'wstoken': token,
            'wsfunction': 'mod_assign_get_assignments'
        }
        res = requests.post(
            'https://moodle.iitb.ac.in/webservice/rest/server.php?moodlewsrestformat=json',
            data=payload)

        table = list()

        for x in json.loads(res.text)['courses']:
            i = 1
            cnt = 0
            for assignment in x['assignments']:
                # assignment is not due
                if datetime.fromtimestamp(
                        assignment['duedate']) < datetime.fromtimestamp(
                            time.time()):
                    continue

                table.append([
                    i, x['shortname'], assignment['name'],
                    datetime.fromtimestamp(assignment['duedate'])
                ])
                table.append([])
                i += 1
                cnt += 1

            if cnt > 0:
                table.append([])

        return (tabulate(
            table, headers=['sl No', 'Course Name', 'Assignment', 'Due Date']))
Exemple #6
0
    def show_discussions_from_a_forum(self,
                                      forum_id,
                                      sender_whatsapp_no,
                                      n=None):
        '''
        Show all discussions of a particular discussion forum
        Input:
            forum_id (int) : ID of the discussion forum
            n (int) : show only top `n` discussions
        '''
        token, userid = Users(sender_whatsapp_no).getMoodle()
        if token == -1:
            return "Please register moodle credentials"

        print("userid:", token, userid)
        if token is None:
            return "Please update Moodle Credentials"

        try:
            payload = {
                'wstoken': token,
                'wsfunction': 'mod_forum_get_forum_discussions',
                'forumid': forum_id
            }
            res = requests.post(
                'https://moodle.iitb.ac.in/webservice/rest/server.php?moodlewsrestformat=json',
                data=payload)
            ret = 'Discussions:\n'
            i = 1

            for x in json.loads(res.text)['discussions']:
                if n is not None and int(n) < i:
                    break

                ret += "\t" + f"{i}. [" + str(
                    datetime.fromtimestamp(
                        x['created'])) + '], ' + x['name'] + '\n'
                ret += bs(x['message'], 'html.parser').get_text() + '\n\n'
                i += 1
        except:
            pass

        return ret
Exemple #7
0
    def show_course_announcements(self, course_id, sender_whatsapp_no, n = None):
        '''
        Show course announcements of a particular course
        Input:
            course_id (int)
            n (int)
        '''
        token, userid = Users(sender_whatsapp_no).getMoodle()
        if token == -1:
            return "Please register moodle credentials"

        print("userid:", token, userid)
        if token is None:
            return "Please update Moodle Credentials"

        payload = {'wstoken': token,'wsfunction':'mod_forum_get_forums_by_courses','courseids[0]': course_id}

        res = requests.post('https://moodle.iitb.ac.in/webservice/rest/server.php?moodlewsrestformat=json',data=payload)

        id = None
        for x in json.loads(res.text):
            if 'announce' in x['name'].lower():
                id = x['id']
                break

        if id is None:
            return ("Course does not exist")
        else:
            payload = {'wstoken': token,'wsfunction':'mod_forum_get_forum_discussions', 'forumid': id}

            res = requests.post('https://moodle.iitb.ac.in/webservice/rest/server.php?moodlewsrestformat=json', data=payload)
            ret = 'Announcements:\n'
            i = 1
            for x in json.loads(res.text)['discussions']:
                if n is not None and int(n) < i:
                    break

                ret += "\t" f"{i}. [" + str(datetime.fromtimestamp(x['created'])) + "] " + x['name'] + '\n'
                ret +=  bs(x['message'],'html.parser').get_text() + '\n\n'
                i += 1

        return ret
Exemple #8
0
    def show_grades(self, sender_whatsapp_no, course_id):
        '''
        Show grades of a course
        Input:
            course_id (int) : ID of the course
        '''
        token, userid = Users(sender_whatsapp_no).getMoodle()
        if token == -1:
            return "Please register moodle credentials"

        print("userid:", token, userid)
        if token is None:
            return "Please update Moodle Credentials"

        try:
            payload = {
                'wstoken': token,
                'wsfunction': 'gradereport_user_get_grade_items',
                'courseid': course_id,
                'userid': userid
            }
            res = requests.post(
                'https://moodle.iitb.ac.in/webservice/rest/server.php?moodlewsrestformat=json',
                data=payload)
            table = list()

            for x in json.loads(res.text)['usergrades']:
                i = 1
                for grades in x['gradeitems']:
                    table.append([
                        i, grades['graderaw'], grades['grademax'],
                        grades['percentageformatted']
                    ])
                    i += 1
                break

            return (tabulate(table,
                             headers=['sl No', 'Grade', 'Max', 'Percentage']))
        except:
            pass
Exemple #9
0
    def show_course_discussion_forums(self,
                                      course_id,
                                      sender_whatsapp_no,
                                      n=None):
        '''
        Show all discussion forums of a particular course
        Input:
            course_id (int) : ID of the course
            n (int) : show only top `n` discussion forums
        '''
        token, userid = Users(sender_whatsapp_no).getMoodle()
        if token == -1:
            return "Please register moodle credentials"

        print("userid:", token, userid)
        if token is None:
            return "Please update Moodle Credentials"

        try:
            payload = {
                'wstoken': token,
                'wsfunction': 'mod_forum_get_forums_by_courses',
                'courseids[0]': course_id
            }
            res = requests.post(
                'https://moodle.iitb.ac.in/webservice/rest/server.php?moodlewsrestformat=json',
                data=payload)
            table = []
            i = 1
            for x in json.loads(res.text):
                if n is not None and int(n) < i:
                    break

                table.append([x['id'], x['name']])
                i += 1

            return (tabulate(table, headers=["Forum ID", "Forum Name"]))
        except:
            pass
Exemple #10
0
    def send_m(self,
               targets,
               subject,
               body,
               attach,
               sender_whatsapp_no,
               filepath=None,
               cc=[],
               bcc=[]):
        try:
            ret = ""
            #Fetch username and password from whatsapp number
            user = Users(sender_whatsapp_no)
            username, password = user.getLDAP()

            if username is None or password is None:
                return "Please register department email credentials"

            #Smtp url and port
            host = 'smtp-auth.iitb.ac.in'
            port = int(587)

            sender = username
            targets = str(targets)
            targets = targets.split(',')

            #Message treated as multipart
            msg = MIMEMultipart()
            msg['Subject'] = subject
            msg['From'] = sender
            msg['To'] = ', '.join(targets)

            #If mail contains cc
            if cc is not None:
                cc = str(cc)
                cc = cc.split(',')
                msg['CC'] = ', '.join(cc)
                targets = targets + cc

            #If mail contains bcc
            if bcc is not None:
                bcc = str(bcc)
                bcc = bcc.split(',')
                msg['BCC'] = ', '.join(bcc)
                targets = targets + bcc

            #If mail contains body
            if body is not None:
                Body = body
                txt = MIMEText(Body)
                msg.attach(txt)

            #If mail contains attachments
            if attach == True:
                filepath = str(filepath)
                #Split for multiple attachments
                path = filepath.split(',')
                for pt in path:
                    type_file = pt.split('.')[-1]
                    #Txt type attachment
                    if type_file == 'txt':
                        with open(pt, "rb") as f:
                            file1 = MIMEApplication(
                                f.read(),
                                _subtype='octet-stream',
                                _encoder=encoders.encode_base64,
                            )
                            file1.add_header('Content-Disposition',
                                             'attachment',
                                             filename=os.path.basename(pt))
                            msg.attach(file1)

                    #Image type attachment
                    elif type_file == 'jpg' or type_file == 'png':
                        with open(pt, 'rb') as f:
                            file1 = MIMEImage(f.read())
                            file1.add_header('Content-Disposition',
                                             'attachment',
                                             filename=os.path.basename(pt))
                            msg.attach(file1)

                    #All other types of attachment
                    else:
                        with open(pt, "rb") as f:
                            file1 = MIMEApplication(f.read(),
                                                    _subtype=type_file)
                            file1.add_header('Content-Disposition',
                                             'attachment',
                                             filename=os.path.basename(pt))
                            msg.attach(file1)
            #Establishing smtp connection using STARTTLS
            server = smtplib.SMTP(host, port)
            server.starttls(context=ssl.create_default_context())

            #Authentication using username and password
            server.login(username, password)
            server.sendmail(sender, targets, msg.as_string())
            ret = ret + "Email sent successfully !!!"
            #Connection close
            server.quit()

        except:
            ret = ret + "Sending failed !! Check username / password / filepath"
            os.remove("configs/dept_mail")
            os.remove("configs/dept_mail.key")
        return ret
Exemple #11
0
    def keyword(self, key, sender_whatsapp_no, limit=5):
        try:
            ret = ""
            #Get key string to filter subject
            s = str(key)

            #Fetch username and password from whatsapp number
            user = Users(sender_whatsapp_no)
            username, password = user.getLDAP()

            if username is None or password is None:
                return "Please register IITB email credentials"

            #Imap url and port
            imap_url = 'imap.iitb.ac.in'
            incoming_port = int(993)

            #Establish connection
            connection = imaplib.IMAP4_SSL(imap_url, incoming_port)

            # Authentication using username and password
            connection.login(username, password)

            # Select Inbox for the connection
            status, messages = connection.select("INBOX")

            # Total number of emails
            messages = int(messages[0])
            j = 0
            try:
                for i in range(messages, 0, -1):

                    # Fetch emails by ID
                    res, msg = connection.fetch(str(i), "(RFC822)")
                    for response in msg:
                        if isinstance(response, tuple):

                            # Parse a bytes email into a message object
                            msg = email.message_from_bytes(response[1])

                            # Decode the email subject
                            subject = decode_header(msg["Subject"])[0][0]

                            if isinstance(subject, bytes):
                                # If subject is byte decode it to string
                                subject = subject.decode()

                            # Fetch information of Emails
                            from_ = msg.get("From")
                            dt = msg.get("Date")
                            sub = subject.lower()

                            # If Email has multiple part
                            if msg.is_multipart():
                                # Span over each part

                                for part in msg.walk():
                                    # Fetch content type
                                    content_type = part.get_content_type()
                                    content_disposition = str(
                                        part.get("Content-Disposition"))
                                    try:
                                        # Fetch body of Email
                                        body = part.get_payload(
                                            decode=True).decode()
                                    except:
                                        pass
                                    if content_type == "text/plain" and "attachment" not in content_disposition:
                                        body = str(body).lower()

                                        #Body matching with given string
                                        if body.__contains__(s):
                                            #Checking for limit of mails
                                            if j >= limit:
                                                raise StopIteration
                                            j = j + 1
                                            ret = ret + ("\n" + "=" * 25)
                                            st = "Message Number :- " + str(j)

                                            ret = ret + ("\n" + str(st) + "\n")
                                            ret = ret + ("\n" + "=" * 25 +
                                                         "\n")
                                            ret = ret + ("\n" + "Subject : " +
                                                         str(subject) + "\n" +
                                                         "Date : " + str(dt) +
                                                         "\n" + "From : " +
                                                         str(from_) + "\n")
                                            # Print text/plain emails and skip attachments
                                            ret = ret + ("\n" + str(body) +
                                                         "\n")

                                        elif "attachment" in content_disposition:
                                            # Download attachments and save in local file
                                            filename = part.get_filename()
                                            if filename:
                                                if not os.path.isdir(subject):
                                                    # Make folder with name as subject
                                                    os.mkdir(subject)
                                                filepath = os.path.join(
                                                    subject, filename)
                                                # Download attachment and save it
                                                open(filepath, "wb").write(
                                                    part.get_payload(
                                                        decode=True))
                            else:
                                # Fetch content type
                                content_type = msg.get_content_type()

                                # Fetch body of Email
                                body = msg.get_payload(decode=True).decode()
                                if content_type == "text/plain":
                                    body = str(body)
                                    #Body matching with given string
                                    if body.__contains__(s):

                                        #Checking for limit of mails
                                        if j >= limit:
                                            raise StopIteration
                                        j = j + 1
                                        ret = ret + ("\n" + "=" * 25 + "\n")
                                        st = "Message Number :- " + str(j)

                                        ret = ret + ("\n" + str(st) + "\n")
                                        ret = ret + ("\n" + "=" * 25 + "\n")
                                        ret = ret + ("\n" + "Subject : " +
                                                     str(subject) + "\n" +
                                                     "Date : " + str(dt) +
                                                     "\n" + "From : " +
                                                     str(from_) + "\n")
                                        ret = ret + ("\n" + str(body) + "\n")

                        else:
                            pass
            # Stop when limit reached
            except StopIteration:
                pass
            #Close connection and logout
            connection.close()
            connection.logout()
        except:
            print("Invalid username / password ")
            os.remove("configs/dept_mail")
            os.remove("configs/dept_mail.key")
        return ret
Exemple #12
0
    def top(self, sender_whatsapp_no, N=5):
        ret = ""
        try:
            #Fetch username and password from whatsapp number
            user = Users(sender_whatsapp_no)
            username, password = user.getLDAP()
            if username is None or password is None:
                return "Please register IITB email credentials"

            #Imap url and port
            imap_url = 'imap.iitb.ac.in'
            incoming_port = int(993)

            #Establish connection
            connection = imaplib.IMAP4_SSL(imap_url, incoming_port)

            # Authentication using username and password
            connection.login(username, password)

            # Fetch top N mails
            status, messages = connection.select("INBOX")

            #Total number of mails
            messages = int(messages[0])

            for i in range(messages, messages - N, -1):
                # fetch the email message by ID
                ret = ret + ("\n" + "=" * 25)
                st = "Message Number :- " + str(messages - i + 1)

                ret = ret + ("\n" + str(st))
                ret = ret + ("\n" + "=" * 25 + "\n")

                # Fetch emails by ID
                res, msg = connection.fetch(str(i), "(RFC822)")
                for response in msg:
                    if isinstance(response, tuple):
                        # Parse a bytes email into a message object
                        msg = email.message_from_bytes(response[1])

                        # Decode the email subject
                        subject = decode_header(msg["Subject"])[0][0]

                        if isinstance(subject, bytes):
                            # If subject is byte decode it to string
                            subject = subject.decode()

                        # Fetch information of Emails
                        from_ = str(msg.get("From"))
                        dt = msg.get("Date")
                        ret = ret + ("\n" + "Subject : " + str(subject) +
                                     "\n" + "Date : " + str(dt) + "\n" +
                                     "From : " + str(from_) + "\n")

                        # If Email has multiple part
                        if msg.is_multipart():
                            # Span over each part
                            for part in msg.walk():

                                # Fetch content type
                                content_type = part.get_content_type()
                                content_disposition = str(
                                    part.get("Content-Disposition"))
                                try:
                                    # Fetch body of Email
                                    body = part.get_payload(
                                        decode=True).decode()
                                except:
                                    pass
                                if content_type == "text/plain" and "attachment" not in content_disposition:

                                    # Print text/plain emails and skip attachments
                                    ret = ret + (str(body))

                                elif "attachment" in content_disposition:
                                    # Download attachments and save in local file
                                    filename = part.get_filename()
                                    if filename:
                                        if not os.path.isdir(subject):
                                            # Make folder with name as subject
                                            os.mkdir(subject)
                                        filepath = os.path.join(
                                            subject, filename)
                                        # Download attachment and save it
                                        open(filepath, "wb").write(
                                            part.get_payload(decode=True))
                        else:
                            # Fetch content type
                            content_type = msg.get_content_type()

                            # Fetch body of Email
                            body = msg.get_payload(decode=True).decode()
                            if content_type == "text/plain":

                                # Print only text email parts
                                ret = ret + (str(body))

                            if content_type == "text/html":
                                # If mail is HTML type create a new HTML file
                                if not os.path.isdir(subject):
                                    # Make a folder for this email with name as subject
                                    os.mkdir(subject)
                                filename = f"{subject[:50]}.html"
                                filepath = os.path.join(subject, filename)
                                # Write the file
                                open(filepath, "w").write(body)

            #Close connection and logout
            connection.close()
            connection.logout()
        except:
            print("Invalid username / password ")
            os.remove("configs/dept_mail")
            os.remove("configs/dept_mail.key")

        return ret
Exemple #13
0
    def date_(self, date1, date2, sender_whatsapp_no, limit=5):
        ret = ""
        try:
            #Get strings of dates
            s1 = str(date1)
            s2 = str(date2)
            t1 = datetime.datetime(int(s1[4:]), int(s1[2:4]), int(s1[0:2]))
            t2 = datetime.datetime(int(s2[4:]), int(s2[2:4]), int(s2[0:2]))

            #Fetch username and password from whatsapp number
            user = Users(sender_whatsapp_no)
            username, password = user.getCSEMail()

            if username is None or password is None:
                return "Please register department email credentials"

            #Imap url and port
            imap_url = 'imap.cse.iitb.ac.in'
            incoming_port = int(993)

            #Establish connection
            connection = imaplib.IMAP4_SSL(imap_url, incoming_port)

            # Authentication using username and password
            connection.login(username, password)

            # Select Inbox for the connection
            status, messages = connection.select("INBOX")

            # Total number of emails
            messages = int(messages[0])
            j = 0
            try:
                for i in range(messages, 0, -1):

                    # Fetch emails by ID
                    res, msg = connection.fetch(str(i), "(RFC822)")
                    for response in msg:

                        if isinstance(response, tuple):

                            # Parse a bytes email into a message object
                            msg = email.message_from_bytes(response[1])
                            # Decode the email subject
                            subject = decode_header(msg["Subject"])[0][0]

                            if isinstance(subject, bytes):
                                # If subject is byte decode it to string
                                subject = subject.decode()

                            # Fetch information of Emails
                            from_ = msg.get("From")
                            dt = msg.get("Date")

                            date_ = str(msg.get("Date"))[0:16]
                            if date_[7] != ' ':
                                date_ = date_[0:5] + '0' + date_[5:15]
                            date_dt1 = datetime.datetime.strptime(
                                date_, '%a, %d %b %Y')

                            #If you reach date less than first date stop
                            if date_dt1 < t1:
                                raise StopIteration

                            #Check range of dates between t1 and t2
                            if date_dt1 >= t1 and date_dt1 <= t2:
                                #Checking for limit of mails
                                if j >= limit:
                                    raise StopIteration

                                j = j + 1
                                ret = ret + ("\n" + "=" * 25)
                                st = "Message Number :- " + str(j)
                                ret = ret + ("\n" + str(st))
                                ret = ret + ("\n" + "=" * 25 + "\n")
                                ret = ret + ("\n" + "Subject : " +
                                             str(subject) + "\n" + "Date : " +
                                             str(dt) + "\n" + "From : " +
                                             str(from_) + "\n")
                                # if the email message is multipart
                                # If Email has multiple part
                                if msg.is_multipart():
                                    # Span over each part

                                    for part in msg.walk():
                                        # Fetch content type
                                        content_type = part.get_content_type()
                                        content_disposition = str(
                                            part.get("Content-Disposition"))
                                        try:
                                            # Fetch body of Email
                                            body = part.get_payload(
                                                decode=True).decode()
                                        except:
                                            pass
                                        if content_type == "text/plain" and "attachment" not in content_disposition:

                                            # Print text/plain emails and skip attachments
                                            ret = ret + ("\n" + str(body) +
                                                         "\n")
                                        elif "attachment" in content_disposition:
                                            # Download attachments and save in local file
                                            filename = part.get_filename()
                                            if filename:
                                                if not os.path.isdir(subject):
                                                    # Make folder with name as subject
                                                    os.mkdir(subject)
                                                filepath = os.path.join(
                                                    subject, filename)
                                                # Download attachment and save it
                                                open(filepath, "wb").write(
                                                    part.get_payload(
                                                        decode=True))
                                else:
                                    # Fetch content type
                                    content_type = msg.get_content_type()

                                    # Fetch body of Email
                                    body = msg.get_payload(
                                        decode=True).decode()
                                    if content_type == "text/plain":
                                        # Print only text email parts
                                        ret = ret + ("\n" + str(body) + "\n")
                                    if content_type == "text/html":
                                        # If mail is HTML type create a new HTML file
                                        if not os.path.isdir(subject):
                                            # Make a folder for this email with name as subject
                                            os.mkdir(subject)
                                        filename = f"{subject[:50]}.html"
                                        filepath = os.path.join(
                                            subject, filename)
                                        # Write the file
                                        open(filepath, "w").write(body)

                            else:
                                pass
            # Stop when limit reached
            except StopIteration:
                pass
            #Close connection and logout
            connection.close()
            connection.logout()
        except:
            print("Invalid username / password ")
            os.remove("configs/dept_mail")
            os.remove("configs/dept_mail.key")
        return ret