Example #1
0
    def subject(self, sub, sender_whatsapp_no, limit=5):
        ret = ""
        try:
            #Get s string to filter subject
            s = str(sub)

            #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")
                            sub = subject.lower()
                            #Subject matching with given string
                            if sub.__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")

                                # 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
Example #2
0
    def send_m(self,targets,subject,body,attach,sender_whatsapp_no,filepath=None,cc=[],bcc=[]):
        try:
            ret=""

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

            if sender is None or passwd is None:
                return "Please register department email credentials"

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

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

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

            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())
            #Connection close
            ret=ret+"Email sent successfully !!!"
            server.quit()

        except:
            ret=ret+"Sending failed !! Check username / password / filepath"
            os.remove("configs/dept_mail")
            os.remove("configs/dept_mail.key")
        return ret