Beispiel #1
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
Beispiel #2
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
Beispiel #3
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
Beispiel #4
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.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")

                            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