def assert_plain_email( email_str: str, email: str, name: str, subject: str, message: str, sender_email: str, to_email: str, to_name: str, ) -> None: p = parser.Parser() mail = p.parsestr(email_str) mail_headers = {h[0]: h[1] for h in mail._headers} assert "multipart/mixed" in mail_headers["Content-Type"] assert mail_headers["MIME-Version"] == "1.0" assert mail_headers["Date"] assert name in mail_headers["From"] assert sender_email in mail_headers["From"] assert to_email in mail_headers["To"] assert to_name in mail_headers["To"] assert name in mail_headers["Reply-To"] assert email in mail_headers["Reply-To"] assert mail_headers["Subject"] assert mail.preamble == "This is a multi-part message in MIME format.\n" body = mail._payload[0] body_headers = {h[0]: h[1] for h in body._headers} assert body_headers["Content-Type"] == 'text/plain; charset="utf-8"' assert body_headers["MIME-Version"] == "1.0" assert body_headers["Content-Transfer-Encoding"] == "base64" body_payload = b64decode(body._payload).decode("utf-8") assert body_payload == message
def test_send_email_with_reply_to(self, smtp): action = std.SendEmailAction( from_addr=self.from_addr, to_addrs=self.to_addrs, reply_to=self.reply_to, bcc_addrs=self.bcc_addrs, smtp_server=self.smtp_server, smtp_password=None, subject=self.subject, body=self.body ) action.run(self.ctx) smtp.assert_called_once_with(self.smtp_server) sendmail = smtp.return_value.sendmail self.assertTrue(sendmail.called, "should call sendmail") self.assertEqual( self.from_addr, sendmail.call_args[1]['from_addr']) message = parser.Parser().parsestr(sendmail.call_args[1]['msg']) self.assertEqual(self.from_addr, message['from']) self.assertEqual(self.to_addrs_str, message['to']) self.assertEqual(self.reply_to_str, message['reply-to'])
def inner(subDic): for file in os.listdir(subDic): currentPath = os.path.join(subDic, file) # Recurse when encountering a directory if os.path.isdir(currentPath): inner(currentPath) else: # Read the email # If Unicode errors are encountered, replace the byte f = open(currentPath, 'r', errors='replace') # Parse the email content = parser.Parser().parsestr(f.read()) f.close() sender = content['From'] # Go through all the recipient headers for header in ['To', 'cc', 'bcc']: # Check whether the header is empty if (content[header] != None): # Extract the individual recipients receivers = [ name.strip() for name in content[header].split(', ') ] # Add the message to the dictionary for receiver in receivers: key = (sender, receiver) countDict[key] = countDict.get(key, 0) + 1
def get_passcode_from_email(host, username, password): """Retrieve the last essh passcode :rtype : str """ pp = poplib.POP3(host) pp.user(username) pp.pass_(password) count, size = pp.stat() passcode = "" mails = range(count - 12, count + 1)[::-1] for mail in mails: message = pp.retr(mail)[1] if is_essh_email(message): # Concat message pieces: message = "\n".join(message) # Parse message into an email object: message = parser.Parser().parsestr(message) # content format: user: username passcode: 000111 content = message.get_payload(decode=True) pos = content.find("passcode: ") if pos > 0: passcode = content[pos + len("passcode:"):].strip() break pp.quit() return passcode
def test_simple(): snd = '*****@*****.**' rcv = '*****@*****.**' subj = 'This is the test header' bodyFile = 'sample_fileB' bodyHash = do_hash(bodyFile) msg = run_script(snd, rcv, subj, bodyFile) parsed = ep.Parser().parsestr(msg) parsedFrom = None parsedTo = None parsedSubj = None if 'From' in parsed: parsedFrom = parsed['From'] if 'To' in parsed: parsedTo = parsed['To'] if 'Subject' in parsed: parsedSubj = parsed['Subject'] if parsedFrom != snd: print('--- Incorrect From address ---') print(' expected: {e}'.format(e=snd)) print(' received: {a}'.format(a=parsedFrom)) sys.exit(1) if parsedTo != rcv: print('--- Incorrect To address ---') print(' expected: {e}'.format(e=rcv)) print(' received: {a}'.format(a=parsedTo)) sys.exit(1) if parsedSubj != subj: print('--- Incorrect Subject ---') print(' expected: {e}'.format(e=subj)) print(' received: {a}'.format(a=parsedSubj)) sys.exit(1)
def parse_email(raw: [str, bytes]) -> dict: """ Parses the raw data of the email. Some fields may not be parsed. """ if not isinstance(raw, str): raw = raw.decode() # parse most fields msg = parser.Parser().parsestr(raw) # it is <email.message.Message object> result = {k: v for k, v in msg.items()} # parse several fields for k in ["From", "To", "Subject"]: result[k] = [] # this field has a list of values, like: [(b'hello', 'utf-8')] values = header.decode_header(msg[k]) for v in values: if isinstance(v[0], str): _v = v[0] else: _v = v[0].decode(v[1] or 'utf-8') result[k].append(_v) # parse the payload result["Payload"] = parse_payload(msg) return result
def readMail(pop_conn): # get msg from server msgs = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] msgs = ['\n'.join(m[1]) for m in msgs] msgs = [parser.Parser().parsestr(m) for m in msgs] # a list of raw messages pop_conn.quit() # maybe later? return msgs
def print_mails(): pop_conn = poplib.POP3_SSL('pop.mail.ru', 995) pop_conn.user(USERNAME) pop_conn.pass_(PASSWORD) mailbox_size = pop_conn.stat() print("mailbox size is " + str(mailbox_size)) # Get messages from server: messages = [ pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1) ] # Concat message pieces: messages = [b"\n".join(mssg[1]) for mssg in messages] # Parse message intom an email object: messages = [ parser.Parser().parsestr(mssg.decode('utf-8')) for mssg in messages ] for message in messages: print(f"{message['subject']} : {message['From']}\n") print(f"Date : {message['Date']}\n") print(f"To : {message['To']}\n") for part in message.walk(): if part.get_content_type(): body = part.get_payload(decode=True) print(body) pop_conn.quit()
def get_popmail(mailhost): if mail_ssl == False: M = poplib.POP3(mailhost, mail_port) if mail_ssl == True: M = poplib.POP3_SSL(mailhost, mail_port) try: M.user(mail_user) M.pass_(mail_passwd) except: logging.warn(get_timestring() + ' - Unable to log in to pop3 server') return NumMessages = len(M.list()[1]) messages = [M.retr(i) for i in range(1, NumMessages + 1)] messages = ["\n".join(mssg[1]) for mssg in messages] messages = [parser.Parser().parsestr(mssg) for mssg in messages] #loop through messages for message in messages: msg_subj = message['subject'] #check if message starts with DAPNET if msg_subj[:6].upper() == 'DAPNET': #this seems to be a pager message, continue! msg_list = msg_subj.split(set_separator) msg_ric = create_list( msg_list[1].lower()) #call sign must be lower case msg_func = msg_list[2] msg_trx = create_list( msg_list[3].lower()) #transceiver group must be lower case msg_emr = msg_list[4] msg_txt = msg_list[5] send_page(msg_ric, msg_func, msg_trx, msg_emr, msg_txt) clean_popmailbox() M.quit()
def receive(self, username, password): #self.sub_logger("[+] receive start") error not from here, ashed pop_server = poplib.POP3_SSL('pop.gmail.com') pop_server.user(username) pop_server.pass_(password) #self.sub_logger("[+] connected with " + username + ", passw: " + password) #error detected from here messages = [ pop_server.retr(i) for i in range(1, len(pop_server.list()[1]) + 1) ] #self.sub_logger("[+] messages = [pop_server.retr(i)]") messages = ["\n".join(mssg[1]) for mssg in messages] #self.sub_logger("[+] messages = [messages formatting without new line]") messages = [parser.Parser().parsestr(mssg) for mssg in messages] #self.sub_logger("[+] messages = [messages_parsed(i)]") pop_server.quit() #self.sub_logger("[+] messages retrieved from server, formatting started") #to here 26/04/16 msgs_decrypted = list() for msg_coded in messages: msg = self.Message(msg_coded) self.messages.append(msg) msgs_decrypted.append(msg) return msgs_decrypted
def parse_mail(self): """ Retrieves a message's header from the IMAP server and parses its headers in the email header data structure used by the user's filters. This method is invoked by the parent class' constructor. """ # Mail has already been parsed in this case if not (self._headers is None and self.message_flags is None): return True self._processor.log("") self._processor.log("New mail detected with UID {0}:".format(self.uid)) try: ret, data = self._processor.imap.uid('fetch', self.uid, "(FLAGS BODY.PEEK[HEADER])") except self._processor.imap.error as e: # Anything imaplib raises an exception for is fatal here. self._processor.fatal_error("Error retrieving message " "with UID %s: %s" % (self.uid, e)) if ret != 'OK': self._processor.log_error( "Error: Could not retrieve message {0}: {1}".format( self.uid, ret)) return False flags = imaplib.ParseFlags(data[0][0]) if self.message_flags is None: self.message_flags = [] for flag in flags: self.message_flags.append(flag.decode('ascii')) headers = email_parser.Parser().parsestr(data[0][1].decode('ascii'), headersonly=True) if self._headers is None: self._headers = {} for name in headers.keys(): value_parts = [] for header in headers.get_all(name, []): try: for (s, c) in email_header.decode_header(header): # email.header.decode_header in Python 3.x may # return either [(str, None)] or [(bytes, # None), ..., (bytes, encoding)]. We must # compensate for this. if not isinstance(s, str): s = s.decode(c if c else "ascii") value_parts.append(s) except (email_errors.HeaderParseError, LookupError, ValueError): self._processor.log_error( "Error: Could not decode header {0} in message " "UID {1}".format(ascii(header), self.uid)) value_parts.append(header) self._headers[name.lower()] = " ".join(value_parts) return True
def checkEmail(): foundLink = False pop_conn = poplib.POP3_SSL(mailServer) pop_conn.user(account_Email) pop_conn.pass_(account_Password) messages = [ pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1) ] messages = ['\n'.join(map(bytes.decode, mssg[1])) for mssg in messages] messages = [parser.Parser().parsestr(mssg) for mssg in messages] for message in messages: if (str.startswith(message['from'], "Discord") & foundLink == False): print("FOUND " + '"' + message['subject'] + '"') foundLink = True for part in message.walk(): if part.get_content_type(): body = part.get_payload(decode=True) thisbody = str(body) MyHTMLParser().feed(thisbody) break # No need to look for more emails if (foundLink == False): print("Couldnt find email, waiting two seconds:", account_Email) time.sleep(2) pop_conn.quit() checkEmail() elif (foundLink == True): pop_conn.quit() verifyAccount()
def test_send_email(self, smtp): action = std.SendEmailAction( from_addr=self.from_addr, to_addrs=self.to_addrs, smtp_server=self.smtp_server, smtp_password=None, subject=self.subject, body=self.body ) action.run(self.ctx) smtp.assert_called_once_with(self.smtp_server) sendmail = smtp.return_value.sendmail self.assertTrue(sendmail.called, "should call sendmail") self.assertEqual( self.from_addr, sendmail.call_args[1]['from_addr']) self.assertEqual( self.to_addrs, sendmail.call_args[1]['to_addrs']) message = parser.Parser().parsestr(sendmail.call_args[1]['msg']) self.assertEqual(self.from_addr, message['from']) self.assertEqual(self.to_addrs_str, message['to']) self.assertEqual( self.subject, decode_header(message['subject'])[0][0].decode('utf-8') ) self.assertEqual( self.body, base64.b64decode(message.get_payload()).decode('utf-8') )
def download(server, username, password, jsonOutputFile, timeout, shouldDelete): success = 0 failure = 0 conn = connect(server, username, password, timeout) messages = conn.list()[1] log.info("Connected to POP3 server; newMessages=%d" % (len(messages))) for i in range(1, len(messages) + 1): txt = conn.retr(i)[1] msg = parser.Parser().parsestr("\n".join(txt)) log.info( "Reading message; messageIdx=%d; messageSubject=\"%s\"; messageSender=\"%s\"" % (i, msg.get('subject'), msg.get('from'))) successCount = parseAttachments(jsonOutputFile, msg) if successCount > 0: if shouldDelete == 1: log.info( "Deleting successfully parsed DMARC report email; messageIdx=%d; messageSubject=\"%s\"; messageSender=\"%s\"" % (i, msg.get('subject'), msg.get('from'))) conn.dele(i) success = success + successCount else: log.info( "Preserving email message since it is not a DMARC report; messageIdx=%d; messageSubject=\"%s\"; messageSender=\"%s\"" % (i, msg.get('subject'), msg.get('from'))) failure = failure + 1 log.info( "DMARC Results; successfulDmarcEmailCount=%d; skippedEmailCount=%d" % (success, failure)) conn.quit()
def main(run): con = poplib.POP3_SSL("pop.gmail.com") con.user(init.var['user']) con.pass_(init.var['pass']) cmd = "nop" printk.inf("POP3 Console") HelpBanner = [["Commands", "Description", "Example"]] HelpBanner += [["list", "list mails", "list"]] HelpBanner += [["read", "show mail", "retr 2"]] HelpBanner += [["dele", "remove mail", "dele 2"]] GRAPHICAL.CreateTable(HelpBanner) while (cmd != "exit"): cmd = raw_input(ClientPrompt(init.CodeName, "pop")) if cmd == "list": messages = [con.retr(i) for i in range(1, len(con.list()[1]) + 1)] messages = ["\n".join(mssg[1]) for mssg in messages] messages = [parser.Parser().parsestr(mssg) for mssg in messages] for message in messages: print message['subject'] elif cmd[0:4] == "read": for j in con.retr(int(cmd[5:]) + 1)[1]: print j elif cmd[0:4] == "dele": con.dele(int(cmd[5:]) + 1)[1] printk.inf( "email marked for delete ('quit' for exit and delete all email marked)" ) elif cmd == "help": GRAPHICAL.CreateTable(HelpBanner) elif cmd == "quit": con.quit() break
def getMail(self, deleteRead=False, section=None, regex="*"): compiled_regex = re.compile(regex, re.IGNORECASE) messages = [] ''' gets all messages from inbox ''' for i in range(1, len(self.pop_conn.list()[1]) + 1): print "retrieving messages..." #Get messages from server: messages.append(self.pop_conn.retr(i)) ''' convert mails to parsable email format''' #Concat message pieces: messages = ["\n".join(mssg[1]) for mssg in messages] #Parse message into an email object: messages = [parser.Parser().parsestr(mssg) for mssg in messages] ''' match each mail's specified section with specified regex and return first match. Also delete matched mail if deleteRead flag is True''' msgNo = 1 for message in messages: if re.match(regex, message[section]) is not None: print "*****************message " + section + " matched*****************\n ", message[ section] if deleteRead: self.pop_conn.dele(msgNo) return message msgNo = msgNo + 1 return None
def parse_email_header(self, texts): # print 'Texts = {}'.format(texts) headers = parser.Parser().parsestr(texts, headersonly=True) for header in headers.keys(): print '{0} is {1}'.format(header, headers[header]) # print 'Headers Subject = {}'.format(headers['Subject']) return headers
def __init__(self, ui, repotype, path, revs=None): super(gnuarch_source, self).__init__(ui, repotype, path, revs=revs) if not os.path.exists(os.path.join(path, '{arch}')): raise common.NoRepo( _("%s does not look like a GNU Arch repository") % path) # Could use checktool, but we want to check for baz or tla. self.execmd = None if util.findexe('baz'): self.execmd = 'baz' else: if util.findexe('tla'): self.execmd = 'tla' else: raise error.Abort(_('cannot find a GNU Arch tool')) common.commandline.__init__(self, ui, self.execmd) self.path = os.path.realpath(path) self.tmppath = None self.treeversion = None self.lastrev = None self.changes = {} self.parents = {} self.tags = {} self.catlogparser = emailparser.Parser() self.encoding = encoding.encoding self.archives = []
def checkEmail(): import poplib from email import parser pop_conn = poplib.POP3_SSL('###.gmail.com') pop_conn.user('###@gmail.com') pop_conn.pass_('########') #pulls the content from the server messages = [ pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1) ] # puts back together messages for printing messages = ["\n".join(mssg[1]) for mssg in messages] #parses through messages messages = [parser.Parser().parsestr(mssg) for mssg in messages] for message in messages: print(message) pop_conn.quit()
def get_message(service, msg_id, logger) -> email.message.EmailMessage: """ Retrive the email message assicated with the given msg_id :param service: Gmail API connection :type service: object :param msg_id: The id for the requested message. :type msg_id: str :param logger: Logger to pass information. :type logger: object :return: The Email message referenced by mss_id :rtype: email.message.EmailMessage """ try: msg = service.users().messages().get(userId='me', id=msg_id, format='raw').execute() msg_in_bytes = base64.urlsafe_b64decode(msg['raw'].encode('ASCII')) email_tmp = email.message_from_bytes(msg_in_bytes, policy=policy.default) email_parser = parser.Parser(policy=policy.default) resulting_email = email_parser.parsestr(email_tmp.as_string()) return resulting_email except (errors.HttpError, error): logger.error(f"Unable to get message for {msg_id}") return None
def retrieve_email_imap(rand_string): tickets = [] imap = imaplib.IMAP4_SSL(imap_server) imap.login(from_address, from_password) imap.select('inbox') result, data = imap.uid('search', None, '(HEADER Subject %s)' % rand_string) if result == 'OK': if data[0]: #data[0] is a space delimited list of matching message UIDs uids = data[0].split(' ') for uid in uids: result, data = imap.uid('fetch', uid, '(RFC822)') subj = parser.Parser().parsestr(data[0][1])['subject'] m = re.match(subject_re, subj) if m: tickets.append(m.group(1)) imap.uid('store', ','.join(uids), '+FLAGS', '(\\Seen)') #Mark as read imap.uid('store', ','.join(uids), '+FLAGS', '(\\Deleted)') # remove from inbox else: raise Exception imap.close() imap.logout() return tickets
def receiveMailInstruct(robotEMailAccount, PWrobotEMailAccount, delMail=1, subjKeyVect=['INSTRUCT', 'A2H', 'H2A', 'SWP', 'SWPFL', 'HELP', 'CLCT']): # Remeber to add all programmed keywords! try: pop_conn = poplib.POP3_SSL('pop.gmail.com') pop_conn.user(str(robotEMailAccount)) pop_conn.pass_(str(PWrobotEMailAccount)) messages = [pop_conn.retr(i) for i in reversed(range(1, len(pop_conn.list()[1]) + 1))] messages = ["\n".join(mssg[1]) for mssg in messages] messages = [parser.Parser().parsestr(mssg) for mssg in messages] for i, message in enumerate(messages): if delMail==1: pop_conn.dele(i+1) if message['subject'] == 'HELP': return {'values': range(0,2), 'instruct': message['subject'], 'from': message['from']} if message['subject'] in subjKeyVect: print 'Instruction keyword found.' message.set_type('text/plain') try: # works on gmail account from PC prefilter = str(message.get_payload(0)) prefilter = prefilter.split('\n')[3].split(',') except: # works from iphone prefilter = str(message).split('"us-ascii"')[1].split('\n')[2].split(',') postfilter = range(len(prefilter)) for i in range(len(prefilter)): postfilter[i] = int(prefilter[i]) pop_conn.quit() return {'values': postfilter, 'instruct': message['subject'], 'from': message['from']} pop_conn.quit() return except: return None
def _DeserializeResponse(self, payload): """Convert string into Response and content. Args: payload: Header and body string to be deserialized. Returns: A Response object """ # Strip off the status line. status_line, payload = payload.split('\n', 1) _, status, _ = status_line.split(' ', 2) # Parse the rest of the response. parser = email_parser.Parser() msg = parser.parsestr(payload) # Get the headers. info = dict(msg) info['status'] = status # Create Response from the parsed headers. content = msg.get_payload() return http_wrapper.Response(info, content, self.__batch_url)
def test_1(self): # navigate to the application home page self.driver.get(self.signup_URL) # To do: check if correct page is loaded # click on the signup button self.driver.find_element_by_link_text(self.signup_btn_id).click() # To do: check if correct page is loaded time.sleep(10) # Find all ids on sign up page first_name = self.driver.find_element_by_id(self.signup_first_name_id) last_name = self.driver.find_element_by_id(self.signup_last_name_id) email = self.driver.find_element_by_id(self.signup_email_id) company = self.driver.find_element_by_id(self.company_id) password = self.driver.find_element_by_id(self.password_id) radio = self.driver.find_element_by_css_selector( self.purchased_radio_id) eula = self.driver.find_element_by_id(self.eula_id) signup = self.driver.find_element_by_id(self.submit_id) # Fill sign up form first_name.send_keys(self.first_name) last_name.send_keys(self.last_name) email.send_keys(self.email) company.send_keys(self.company_name) password.send_keys(self.password) radio.click() eula.click() signup.click() self.driver.delete_all_cookies time.sleep(10) # Check if confirmation email has been sent to original email pop_conn = poplib.POP3_SSL('pop.gmail.com') pop_conn.user(self.uname) pop_conn.pass_(self.password) # Get messages from server: messages = [ pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1) ] # Concat message pieces: messages = ["\n".join(mssg[1]) for mssg in messages] # Parse message intom an email object: messages = [parser.Parser().parsestr(mssg) for mssg in messages] for message in messages: to = self.receiver_name + ' <' + self.email + '>' if message['to'] == to: # extract URL url = re.search("(?P<url>https?://[^\s]+)", str(message)).group("url") break pop_conn.quit() self.second_driver.get(url) # check if you can successfully log in on Apptimize platform using # confirmation mail login_email = self.second_driver.find_element_by_id( self.login_email_id) login_email.send_keys(self.original_email) pwd = self.second_driver.find_element_by_id(self.login_password_id) pwd.send_keys(self.password) btn = self.second_driver.find_element_by_id(self.login_btn_id) btn.click()
def _Execute(self, http): """Serialize batch request, send to server, process response. Args: http: A httplib2.Http object to be used to make the request with. Raises: httplib2.HttpLib2Error if a transport error has occured. apiclient.errors.BatchError if the response is the wrong format. """ message = mime_multipart.MIMEMultipart('mixed') # Message should not write out its own headers. setattr(message, '_write_headers', lambda self: None) # Add all the individual requests. for key in self.__request_response_handlers: msg = mime_nonmultipart.MIMENonMultipart('application', 'http') msg['Content-Transfer-Encoding'] = 'binary' msg['Content-ID'] = self._ConvertIdToHeader(key) body = self._SerializeRequest( self.__request_response_handlers[key].request) msg.set_payload(body) message.attach(msg) request = http_wrapper.Request(self.__batch_url, 'POST') request.body = message.as_string() request.headers['content-type'] = ( 'multipart/mixed; boundary="%s"') % message.get_boundary() response = http_wrapper.MakeRequest(http, request) if response.status_code >= 300: raise exceptions.HttpError.FromResponse(response) # Prepend with a content-type header so Parser can handle it. header = 'content-type: %s\r\n\r\n' % response.info['content-type'] content = response.content if isinstance(content, bytes) and self.__response_encoding: content = response.content.decode(self.__response_encoding) parser = email_parser.Parser() mime_response = parser.parsestr(header + content) if not mime_response.is_multipart(): raise exceptions.BatchError( 'Response not in multipart/mixed format.') for part in mime_response.get_payload(): request_id = self._ConvertHeaderToId(part['Content-ID']) response = self._DeserializeResponse(part.get_payload()) # Disable protected access because namedtuple._replace(...) # is not actually meant to be protected. # pylint: disable=protected-access self.__request_response_handlers[request_id] = ( self.__request_response_handlers[request_id]._replace( response=response))
def __init__(self, maildir, limit=None, skip=0, file_func=lambda x: True): super().__init__(maildir, limit, skip) self.email_parser = ep.Parser() self.file_func = lambda filename: '.quagga.' not in filename and file_func( filename) self.email_func = lambda path, filename, file: EmailMessage( path, filename, self.email_parser.parsestr(file)) self.length = sum( [len(files) for r, d, files in os.walk(self.maildir)])
def retrieveMessages(identity_dict): output_dir = 'incoming' pop_conn = poplib.POP3_SSL(identity_dict['POP3']) pop_conn.user(identity_dict['Username']) pop_conn.pass_(identity_dict['Password']) messages = [ pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1) ] print messages [pop_conn.dele(i) for i in range(1, len(pop_conn.list()[1]) + 1)] pop_conn.quit() messages = ["\n".join(mssg[1]) for mssg in messages] messages = [parser.Parser().parsestr(mssg) for mssg in messages] for msg in messages: replyto_addr = None output = "" unique_id = str(random.choice(xrange(1, 999999999))) if msg['Reply-To']: replyto_addr = msg['Reply-To'] else: replyto_addr = msg['From'] output += "From: " + replyto_addr + os.linesep output += "To: " + msg['To'] + os.linesep output += "Date: " + msg['Date'] + os.linesep output += "Subject: " + msg['Subject'] + os.linesep output += os.linesep try: output += msg.get_payload() except: payload = msg.get_payload() found = False if payload: for part in payload: print "before if" if 'Content-type' in part and "text/plain" in part[ 'Content-type']: print "After if" output += part.get_payload() found = True break if not found: for part in payload: if 'Content-type' in part and "text/html" in part[ 'Content-type']: output += part.get_payload() break print output tmpName, realName = output_dir + '/' + 'IDENTITY' + '-' + unique_id + '.tmp', output_dir + '/' + 'IDENTITY' + '-' + unique_id + '.ready' f = open(tmpName, 'w') f.write(output) f.flush() os.fsync(f) f.close() os.rename(tmpName, realName) return
def get_latest_email(sender=None, email_config_=None): print "Starting to fetch the latest email!" email_config = default_email_config if email_config_ is None else email_config_ handler = poplib.POP3(email_config.email_server.pop_server, timeout=10) handler.user(email_config.user_config.user_account) handler.pass_(email_config.user_config.password) count, size = handler.stat() print 'Response from server: Email total count %s, total size %s\n' % (count, size) if count == 0: print "No mail in mail box!" return None if sender is None: return parser.Parser().parsestr('\n'.join(handler.retr(count)[1])) # At most search in last ten email end = count - 10 if count > 10 else 1 for i in range(count, end, -1): mail_tmp = parser.Parser().parsestr('\n'.join(handler.retr(i)[1])) if sender in mail_tmp['From']: return mail_tmp
def parse_message(message_in): parsed_message = parser.Parser().parsestr("\n".join(message_in[1])) """ NOTE: at this stage, easy to get some information such as: - From: parsed_message['From'] - Date: parsed_message['Date'] """ return (parsed_message)
def email(recipients, body): message = email_parser.Parser().parsestr(body.encode('utf-8')) addrs = [] # Get rid of 8-bit chars in the email address fields. for addr_header in email_addr_headers: addrs = message.get_all(addr_header) if not addrs or is_7bit(', '.join(addrs)): continue del message[addr_header] encoded_addrs = ', '.join([encode_addr(a) for a in addrs]) message[addr_header] = encoded_addrs # Get rid of 8-bit chars in the other message headers. for header_name in set(message.keys()): headers = message.get_all(header_name) if is_7bit(''.join(headers)): continue del message[header_name] for utf_header in headers: if is_7bit(''.join(headers)): ascii_header = utf_header else: ascii_header = encode_header(utf_header) message[header_name] = ascii_header # If the body isn't plain ascii, encode it as well. if not message.get_charset(): email_body = message.get_payload() if not is_7bit(email_body): message.set_charset('utf-8') # Default the recipients to the 'To', etc headers in the email. if not recipients: addrs = [] for recipient_header in recipient_addr_headers: addrs.extend(message.get_all(recipient_header, [])) addrs = email_utils.getaddresses(addrs) recipients = [email_utils.formataddr(a) for a in addrs] elif type(recipients) in (str, unicode): recipients = [recipients] # # If lca_info.py:bcc_email is set, send it there as well. # if lca_info['bcc_email']: recipients.append(lca_info['bcc_email']) # send the email using smtp try: s = smtplib.SMTP(config['smtp_server']) s.sendmail(lca_info['contact_email'], recipients, message.as_string()) s.quit() except Exception as e: h.flash( 'Unable to send email. ' 'Please contact %s' % lca_info['webmaster_email'], 'error' ) traceback.print_exc()