Python email.message() Examples
The following are 30
code examples of email.message().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
email
, or try the search function
.
Example #1
Source File: test_email_renamed.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_get_decoded_payload(self): eq = self.assertEqual msg = self._msgobj('msg_10.txt') # The outer message is a multipart eq(msg.get_payload(decode=True), None) # Subpart 1 is 7bit encoded eq(msg.get_payload(0).get_payload(decode=True), 'This is a 7bit encoded message.\n') # Subpart 2 is quopri eq(msg.get_payload(1).get_payload(decode=True), '\xa1This is a Quoted Printable encoded message!\n') # Subpart 3 is base64 eq(msg.get_payload(2).get_payload(decode=True), 'This is a Base64 encoded message.') # Subpart 4 is base64 with a trailing newline, which # used to be stripped (issue 7143). eq(msg.get_payload(3).get_payload(decode=True), 'This is a Base64 encoded message.\n') # Subpart 5 has no Content-Transfer-Encoding: header. eq(msg.get_payload(4).get_payload(decode=True), 'This has no Content-Transfer-Encoding: header.\n')
Example #2
Source File: blob_upload_test.py From browserscope with Apache License 2.0 | 6 votes |
def test_check_line_endings(self): """Ensure the upload message uses correct RFC-2821 line terminators.""" # Create upload. upload_data = ( """--================1234== Content-Type: text/plain MIME-Version: 1.0 Content-Disposition: form-data; name="field1"; filename="stuff.txt" value --================1234==--""") upload_url = blobstore.create_upload_url('/success') request_path = urlparse.urlparse(upload_url)[2] self.environ['PATH_INFO'] = request_path self.environ['CONTENT_TYPE'] = ( 'multipart/form-data; boundary="================1234=="') status, _, _, _, forward_body = self.run_dispatcher(upload_data) self.assertEquals('200 OK', status) forward_body = forward_body.replace('\r\n', '') self.assertEqual(forward_body.rfind('\n'), -1)
Example #3
Source File: blob_upload_test.py From browserscope with Apache License 2.0 | 6 votes |
def test_base64(self): """Test automatic decoding of a base-64-encoded message.""" # Create upload. upload_data = ( """--================1234== Content-Type: text/plain MIME-Version: 1.0 Content-Disposition: form-data; name="field1"; filename="stuff.txt" Content-Transfer-Encoding: base64 %s --================1234==--""" % base64.urlsafe_b64encode('value')) upload_url = blobstore.create_upload_url('/success') upload, forward_environ, _ = self._run_test_success( upload_data, upload_url) self.assertEquals('/success', forward_environ['PATH_INFO']) self.assertEquals( ('form-data', {'filename': 'stuff.txt', 'name': 'field1'}), cgi.parse_header(upload['content-disposition']))
Example #4
Source File: mailbox.py From meddle with MIT License | 6 votes |
def remove_folder(self, folder): """Delete the named folder, which must be empty.""" path = os.path.join(self._path, '.' + folder) for entry in os.listdir(os.path.join(path, 'new')) + \ os.listdir(os.path.join(path, 'cur')): if len(entry) < 1 or entry[0] != '.': raise NotEmptyError('Folder contains message(s): %s' % folder) for entry in os.listdir(path): if entry != 'new' and entry != 'cur' and entry != 'tmp' and \ os.path.isdir(os.path.join(path, entry)): raise NotEmptyError("Folder contains subdirectory '%s': %s" % (folder, entry)) for root, dirs, files in os.walk(path, topdown=False): for entry in files: os.remove(os.path.join(root, entry)) for entry in dirs: os.rmdir(os.path.join(root, entry)) os.rmdir(path)
Example #5
Source File: email_utils.py From app with MIT License | 6 votes |
def get_spam_info(msg: Message) -> (bool, str): """parse SpamAssassin header to detect whether a message is classified as spam. Return (is spam, spam status detail) The header format is ```X-Spam-Status: No, score=-0.1 required=5.0 tests=DKIM_SIGNED,DKIM_VALID, DKIM_VALID_AU,RCVD_IN_DNSWL_BLOCKED,RCVD_IN_MSPIKE_H2,SPF_PASS, URIBL_BLOCKED autolearn=unavailable autolearn_force=no version=3.4.2``` """ spamassassin_status = msg["X-Spam-Status"] if not spamassassin_status: return False, "" # yes or no spamassassin_answer = spamassassin_status[: spamassassin_status.find(",")] return spamassassin_answer.lower() == "yes", spamassassin_status
Example #6
Source File: email_handler.py From app with MIT License | 6 votes |
def handle_DATA(self, server, session, envelope: Envelope): LOG.debug( "===>> New message, mail from %s, rctp tos %s ", envelope.mail_from, envelope.rcpt_tos, ) if POSTFIX_SUBMISSION_TLS: smtp = SMTP(POSTFIX_SERVER, 587) smtp.starttls() else: smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25) app = new_app() with app.app_context(): return handle(envelope, smtp)
Example #7
Source File: email_handler.py From app with MIT License | 6 votes |
def handle_sender_email(envelope: Envelope): filename = ( arrow.now().format("YYYY-MM-DD_HH-mm-ss") + "_" + random_string(10) + ".eml" ) filepath = os.path.join(SENDER_DIR, filename) with open(filepath, "wb") as f: f.write(envelope.original_content) LOG.d("Write email to sender at %s", filepath) msg = email.message_from_bytes(envelope.original_content) orig = get_orig_message_from_bounce(msg) if orig: LOG.warning( "Original message %s -> %s saved at %s", orig["From"], orig["To"], filepath ) return "250 email to sender accepted"
Example #8
Source File: email_handler.py From app with MIT License | 6 votes |
def replace_str_in_msg(msg: Message, fr: str, to: str): if msg.get_content_maintype() != "text": return msg new_body = msg.get_payload(decode=True).replace(fr.encode(), to.encode()) # If utf-8 decoding fails, do not touch message part try: new_body = new_body.decode("utf-8") except: return msg cte = ( msg["Content-Transfer-Encoding"].lower() if msg["Content-Transfer-Encoding"] else None ) subtype = msg.get_content_subtype() delete_header(msg, "Content-Transfer-Encoding") delete_header(msg, "Content-Type") email.contentmanager.set_text_content(msg, new_body, subtype=subtype, cte=cte) return msg
Example #9
Source File: __init__.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def __init__(self, info): # info is either an email.message or # an httplib.HTTPResponse object. if isinstance(info, http.client.HTTPResponse): for key, value in info.getheaders(): key = key.lower() prev = self.get(key) if prev is not None: value = ", ".join((prev, value)) self[key] = value self.status = info.status self["status"] = str(self.status) self.reason = info.reason self.version = info.version elif isinstance(info, email.message.Message): for key, value in list(info.items()): self[key.lower()] = value self.status = int(self["status"]) else: for key, value in info.items(): self[key.lower()] = value self.status = int(self.get("status", self.status))
Example #10
Source File: mailbox.py From meddle with MIT License | 5 votes |
def __init__(self, message=None): """Initialize an BabylMessage instance.""" self._labels = [] self._visible = Message() Message.__init__(self, message)
Example #11
Source File: mailbox.py From meddle with MIT License | 5 votes |
def get_labels(self): """Return a list of labels on the message.""" return self._labels[:]
Example #12
Source File: mailbox.py From meddle with MIT License | 5 votes |
def _explain_to(self, message): """Copy MH-specific state to message insofar as possible.""" if isinstance(message, MaildirMessage): sequences = set(self.get_sequences()) if 'unseen' in sequences: message.set_subdir('cur') else: message.set_subdir('cur') message.add_flag('S') if 'flagged' in sequences: message.add_flag('F') if 'replied' in sequences: message.add_flag('R') elif isinstance(message, _mboxMMDFMessage): sequences = set(self.get_sequences()) if 'unseen' not in sequences: message.add_flag('RO') else: message.add_flag('O') if 'flagged' in sequences: message.add_flag('F') if 'replied' in sequences: message.add_flag('A') elif isinstance(message, MHMessage): for sequence in self.get_sequences(): message.add_sequence(sequence) elif isinstance(message, BabylMessage): sequences = set(self.get_sequences()) if 'unseen' in sequences: message.add_label('unseen') if 'replied' in sequences: message.add_label('answered') elif isinstance(message, Message): pass else: raise TypeError('Cannot convert to specified type: %s' % type(message))
Example #13
Source File: mailbox.py From meddle with MIT License | 5 votes |
def __init__(self, message=None): """Initialize a Message instance.""" if isinstance(message, email.message.Message): self._become_message(copy.deepcopy(message)) if isinstance(message, Message): message._explain_to(self) elif isinstance(message, str): self._become_message(email.message_from_string(message)) elif hasattr(message, "read"): self._become_message(email.message_from_file(message)) elif message is None: email.message.Message.__init__(self) else: raise TypeError('Invalid message type: %s' % type(message))
Example #14
Source File: mailbox.py From meddle with MIT License | 5 votes |
def _append_message(self, message): """Append message to mailbox and return (start, stop) offsets.""" self._file.seek(0, 2) before = self._file.tell() try: self._pre_message_hook(self._file) offsets = self._install_message(message) self._post_message_hook(self._file) except BaseException: self._file.truncate(before) raise self._file.flush() self._file_length = self._file.tell() # Record current length of mailbox return offsets
Example #15
Source File: mailbox.py From meddle with MIT License | 5 votes |
def _post_message_hook(self, f): """Called after writing each message to file f.""" f.write(os.linesep + '\037')
Example #16
Source File: mailbox.py From meddle with MIT License | 5 votes |
def _pre_message_hook(self, f): """Called before writing each message to file f.""" f.write('\014' + os.linesep)
Example #17
Source File: mailbox.py From meddle with MIT License | 5 votes |
def __setitem__(self, key, message): """Replace the keyed message; raise KeyError if it doesn't exist.""" _singlefileMailbox.__setitem__(self, key, message) if isinstance(message, BabylMessage): self._labels[key] = message.get_labels()
Example #18
Source File: mailbox.py From meddle with MIT License | 5 votes |
def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" _singlefileMailbox.remove(self, key) if key in self._labels: del self._labels[key]
Example #19
Source File: mailbox.py From meddle with MIT License | 5 votes |
def _dump_sequences(self, message, key): """Inspect a new MHMessage and update sequences appropriately.""" pending_sequences = message.get_sequences() all_sequences = self.get_sequences() for name, key_list in all_sequences.iteritems(): if name in pending_sequences: key_list.append(key) elif key in key_list: del key_list[key_list.index(key)] for sequence in pending_sequences: if sequence not in all_sequences: all_sequences[sequence] = [key] self.set_sequences(all_sequences)
Example #20
Source File: mailbox.py From meddle with MIT License | 5 votes |
def add_label(self, label): """Add label to list of labels on the message.""" if isinstance(label, str): if label not in self._labels: self._labels.append(label) else: raise TypeError('label must be a string: %s' % type(label))
Example #21
Source File: mailbox.py From meddle with MIT License | 5 votes |
def has_key(self, key): """Return True if the keyed message exists, False otherwise.""" return os.path.exists(os.path.join(self._path, str(key)))
Example #22
Source File: mailbox.py From meddle with MIT License | 5 votes |
def get_file(self, key): """Return a file-like representation or raise a KeyError.""" try: f = open(os.path.join(self._path, str(key)), 'rb') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise
Example #23
Source File: mailbox.py From meddle with MIT License | 5 votes |
def get_string(self, key): """Return a string representation or raise a KeyError.""" try: if self._locked: f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise
Example #24
Source File: mailbox.py From meddle with MIT License | 5 votes |
def get_message(self, key): """Return a Message representation or raise a KeyError.""" try: if self._locked: f = open(os.path.join(self._path, str(key)), 'r+') else: f = open(os.path.join(self._path, str(key)), 'r') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise
Example #25
Source File: mailbox.py From meddle with MIT License | 5 votes |
def remove(self, key): """Remove the keyed message; raise KeyError if it doesn't exist.""" path = os.path.join(self._path, str(key)) try: f = open(path, 'rb+') except IOError, e: if e.errno == errno.ENOENT: raise KeyError('No message with key: %s' % key) else: raise
Example #26
Source File: mailbox.py From meddle with MIT License | 5 votes |
def add(self, message): """Add message and return assigned key.""" keys = self.keys() if len(keys) == 0: new_key = 1 else: new_key = max(keys) + 1 new_path = os.path.join(self._path, str(new_key)) f = _create_carefully(new_path) closed = False try: if self._locked: _lock_file(f) try: try: self._dump_message(message, f) except BaseException: # Unlock and close so it can be deleted on Windows if self._locked: _unlock_file(f) _sync_close(f) closed = True os.remove(new_path) raise if isinstance(message, MHMessage): self._dump_sequences(message, new_key) finally: if self._locked: _unlock_file(f) finally: if not closed: _sync_close(f) return new_key
Example #27
Source File: mailbox.py From meddle with MIT License | 5 votes |
def _post_message_hook(self, f): """Called after writing each message to file f.""" f.write(os.linesep + '\001\001\001\001' + os.linesep)
Example #28
Source File: mailbox.py From meddle with MIT License | 5 votes |
def _pre_message_hook(self, f): """Called before writing each message to file f.""" f.write('\001\001\001\001' + os.linesep)
Example #29
Source File: mailbox.py From meddle with MIT License | 5 votes |
def _pre_message_hook(self, f): """Called before writing each message to file f.""" if f.tell() != 0: f.write(os.linesep)
Example #30
Source File: mailbox.py From meddle with MIT License | 5 votes |
def has_key(self, key): """Return True if the keyed message exists, False otherwise.""" self._lookup() return key in self._toc