def analyze_msg(raws, a): """ Analyze message. Determine if sender and command are valid. Return values: None: Sender is invalid or no text part False: Invalid command Otherwise: Array: message split by lines :type raws: dict """ print("Analyzing message with uid " + str(a)) msg = pm.factory(raws[a][b'BODY[]']) frm = msg.get_addresses('from') if frm[0][1] != sadr: print("Unread is from %s <%s> skipping" % (frm[0][0], frm[0][1])) return None global subject if not subject.startswith("Re"): subject = "Re: " + msg.get_subject() print("subject is", subject) if msg.text_part is None: print("No text part, cannot parse") return None text = msg.text_part.get_payload().decode(msg.text_part.charset) cmds = text.replace('\r', '').split('\n') # Remove any \r and split on \n if cmds[0] not in commands: print("Command %s is not in commands" % cmds[0]) return False else: return cmds
def execute_email_content(imapObj, uid, passphrase, _continue): rawMsg = imapObj.fetch(uid, ['BODY[]']) msg = PyzMessage.factory(rawMsg[uid][b'BODY[]']) lines = msg.text_part.get_payload().decode('utf-8', 'ignore').split() # check the first line in the email for passphrase if passphrase: logging.debug('passphrase = {}'.format(passphrase)) found = lines.pop(0) if found != passphrase: logging.error( 'Incorrect passphrase provided for uid {}: {}'.format( uid, found)) print('incorrect passphrase provided for email {}.'.format(uid)) return # move onto the next email for num, line in enumerate(lines): try: exec(line) except: logging.error('Error: unable to execute line {}:{}'.format( num, line)) print('Error: unable to execute line {}. Aborting email {}...'. format(num, uid)) add_label(imapObj, uid, 'Error') if _continue: logging.error('Continue flag set. Continuing program..') print('Continue flag set. Continuing program..') return # move onto the next email else: logging.error( 'Continue flag not set. Stop processing emails..') print('Continue flag not set. Stop processing emails..') raise DoNotContinue
def check_emails(imap, unique_ids, verification): """ Check the email body for all unique ids searching for the passphrase stored in the verification variable. If the message contains the passphrase, the body of the message and unique id are added to respective collections (and returned) :param IMAPClient imap: session with user logged in :param list unique_ids: unique ids corresponding with search matches :param dict verification: structure including 2 entries - an email address corresponding to the sender and a passphrase included in the message body """ instructions, remove_ids = [], [] for unique_id in unique_ids: raw_messages = imap.fetch([unique_id], ['BODY[]']) message = PyzMessage.factory(raw_messages[unique_id][b'BODY[]']) text = message.text_part.get_payload().decode('ascii') if verification['passphrase'] in text: if message.html_part: body = message.html_part.get_payload().decode( message.html_part.charset) if message.text_part: body = message.text_part.get_payload().decode( message.text_part.charset) instructions.append(body) remove_ids.append(unique_id) return instructions, remove_ids
def _parse_sent_at(message: PyzMessage) -> Optional[str]: rfc_822 = message.get_decoded_header('date') if not rfc_822: return None date_tz = parsedate_tz(rfc_822) if not date_tz: return None timestamp = mktime_tz(date_tz) # noinspection PyUnresolvedReferences date_utc = datetime.fromtimestamp(timestamp, timezone.utc) return date_utc.strftime('%Y-%m-%d %H:%M')
def __init__(self, peer, envelop_from, envelop_to, source): self._id = str(uuid.uuid4()) self.source = source self.envelope_sender = envelop_from self.envelope_to = envelop_to self.received = datetime.utcnow() # email module self.mail_email = message_from_string(self.source) # pyzmail module self.mail_pyzmail = PyzMessage.factory(self.source)
def parse_mime_email(mime_email: str) -> dict: message = PyzMessage.factory(mime_email) return { 'sent_at': _parse_sent_at(message), 'to': _parse_addresses(message, 'to'), 'cc': _parse_addresses(message, 'cc'), 'bcc': _parse_addresses(message, 'bcc'), 'from': _parse_address(message, 'from'), 'subject': message.get_subject(), 'body': _parse_body(message), 'attachments': list(_parse_attachments(message.mailparts)), }
def send_mails(self): for mail in os.listdir(self.storage): if mail.endswith('.sending'): continue path = os.path.join(self.storage, mail) sending_path = path + '.sending' os.rename(path, sending_path) with open(sending_path) as f: print 'sending %s' % path mail = PyzMessage.factory(f.read()) callback = functools.partial(self._send_callback, path) try: self.send_mail(mail, callback) except Exception, e: print str(e)
def __init__(self, raw_mail_lines): msg_content = b'\r\n'.join(raw_mail_lines) msg = PyzMessage.factory(msg_content) self.subject = msg.get_subject() self.sender = msg.get_address('from') self.date = msg.get_decoded_header('date', '') self.id = msg.get_decoded_header('message-id', '') for mailpart in msg.mailparts: if mailpart.is_body=='text/plain': payload, used_charset=decode_text(mailpart.get_payload(), mailpart.charset, None) self.charset = used_charset self.text = payload return else: self.text = None
def find_instructions(imap_dom, mail, password): instructions, remove_id = [], [] imaplib._MAXLINE = 10_000_000 imap = IMAPClient(imap_dom, ssl=True) imap.login(mail, password) imap.select_folder('INBOX', readonly=False) uids = imap.search(['SUBJECT', 'control']) for item in uids: raw_messages = imap.fetch([item], ['BODY[]']) message = PyzMessage.factory(raw_messages[item][b'BODY[]']) if message.text_part: body = message.text_part.get_payload().decode( message.text_part.charset) instructions.append(body) remove_id.append(id) delete_emails(imap, remove_id) return instructions
def find_urls(imap_dom, mail, password): url = [] imaplib._MAXLINE = 10_000_000 imap = IMAPClient(imap_dom, ssl=True) imap.login(mail, password) imap.select_folder('INBOX', readonly=True) uids = imap.search(['SINCE', '01-Mar-2020']) for n in uids: raw_messages = imap.fetch([n], ['BODY[]']) message = PyzMessage.factory(raw_messages[n][b'BODY[]']) if message.html_part: html = message.html_part.get_payload().decode( message.html_part.charset) soup = BeautifulSoup(html, 'lxml') links = soup.select('a') for link in links: if 'unsubscribe' in link.text.lower(): url.append(link.get('href')) imap.logout() return url
def read(self): limit_UID = JSON_data().read_json() UIDs = self.main_client.search(['ALL'])[-limit_UID['uid_limit']:] print( f"You have {'{:,}'.format(len(self.main_client.search(['ALL'])))} emails in your inbox." ) if UIDs[-1] == 0: UIDs = UIDs[:-1] print(colorama.Fore.YELLOW, f"[!] Getting {'{:,}'.format(len(UIDs))} recent emails...", colorama.Style.RESET_ALL) rawMessage = self.main_client.fetch(UIDs, ['BODY[]', 'FLAGS']) for index, i in enumerate(rawMessage, start=1): try: message = PyzMessage.factory(rawMessage[i][b'BODY[]']) print( colorama.Fore.GREEN, f'\n\n\n#{index}', colorama.Style.RESET_ALL, f" - {message.get_subject()} from: {message.get_addresses('from')[0][0]}\n" ) print(message.text_part.get_payload().decode('utf-8')) except (AttributeError, UnicodeDecodeError): continue
def on_friend_message(self, friend_id, message): mail = PyzMessage.factory(message) mail['X-Tox-Friend-Id'] = str(friend_id) self.mails.add(str(mail)) print 'Mail from %s stored' % mail['X-Tox-Id']
def _parse_addresses(message: PyzMessage, address_type: str) -> List[str]: return [email for _, email in message.get_addresses(address_type) if email]
logging.debug('Start of the program') try: imapObj = gmail_imap_login(args.account, args.password) except Exception as exception: print('Exiting program..') exit() gmail_select_folder(imapObj, args.f, readonly=True) uids = imapObj.gmail_search('unsubscribe') unsubed = [] for uid in uids: logging.debug('Checking email {}'.format(uid)) rawMsg = imapObj.fetch(uid, ['BODY[]']) msg = PyzMessage.factory(rawMsg[uid][b'BODY[]']) src = msg.get_address('from') if src[0] in unsubed: logging.debug('{} already in unsubed. Skippting email {}'.format( src[0], uid)) continue if msg.html_part: soup = bs4.BeautifulSoup(msg.html_part.get_payload().decode( 'utf-8', 'ignore'), features='lxml') url = soup.find( "a", string=["Unsubscribe", "unsubscribe", "UNSUBSCRIBE"]) if url: url = url['href']