當前位置: 首頁>>代碼示例>>Python>>正文


Python mailbox.mbox方法代碼示例

本文整理匯總了Python中mailbox.mbox方法的典型用法代碼示例。如果您正苦於以下問題:Python mailbox.mbox方法的具體用法?Python mailbox.mbox怎麽用?Python mailbox.mbox使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在mailbox的用法示例。


在下文中一共展示了mailbox.mbox方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_file_perms

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def test_file_perms(self):
        # From bug #3228, we want to verify that the mailbox file isn't executable,
        # even if the umask is set to something that would leave executable bits set.
        # We only run this test on platforms that support umask.
        try:
            old_umask = os.umask(0077)
            self._box.close()
            os.unlink(self._path)
            self._box = mailbox.mbox(self._path, create=True)
            self._box.add('')
            self._box.close()
        finally:
            os.umask(old_umask)

        st = os.stat(self._path)
        perms = st.st_mode
        self.assertFalse((perms & 0111)) # Execute bits should all be off. 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:19,代碼來源:test_mailbox.py

示例2: createMessage

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def createMessage(self, dir, mbox=False):
        t = int(time.time() % 1000000)
        pid = self._counter
        self._counter += 1
        filename = os.extsep.join((str(t), str(pid), "myhostname", "mydomain"))
        tmpname = os.path.join(self._dir, "tmp", filename)
        newname = os.path.join(self._dir, dir, filename)
        with open(tmpname, "w") as fp:
            self._msgfiles.append(tmpname)
            if mbox:
                fp.write(FROM_)
            fp.write(DUMMY_MESSAGE)
        if hasattr(os, "link"):
            os.link(tmpname, newname)
        else:
            with open(newname, "w") as fp:
                fp.write(DUMMY_MESSAGE)
        self._msgfiles.append(newname)
        return tmpname 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:21,代碼來源:test_mailbox.py

示例3: test_file_perms

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def test_file_perms(self):
        # From bug #3228, we want to verify that the mailbox file isn't executable,
        # even if the umask is set to something that would leave executable bits set.
        # We only run this test on platforms that support umask.
        if hasattr(os, 'umask') and hasattr(os, 'stat'):
            try:
                old_umask = os.umask(0077)
                self._box.close()
                os.unlink(self._path)
                self._box = mailbox.mbox(self._path, create=True)
                self._box.add('')
                self._box.close()
            finally:
                os.umask(old_umask)

            st = os.stat(self._path)
            perms = st.st_mode
            self.assertFalse((perms & 0111)) # Execute bits should all be off. 
開發者ID:dxwu,項目名稱:BinderFilter,代碼行數:20,代碼來源:test_mailbox.py

示例4: is_mbox

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def is_mbox(path):
    """
    Checks if the given content is a MBOX mailbox file

    Args:
        path: Content to check

    Returns:
        bool: A flag the indicates if a file is a MBOX mailbox file
    """
    _is_mbox = False
    try:
        mbox = mailbox.mbox(path)
        if len(mbox.keys()) > 0:
            _is_mbox = True
    except Exception as e:
        logger.debug("Error checking for MBOX file: {0}".format(e.__str__()))

    return _is_mbox 
開發者ID:domainaware,項目名稱:parsedmarc,代碼行數:21,代碼來源:utils.py

示例5: test_file_perms

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def test_file_perms(self):
        # From bug #3228, we want to verify that the mailbox file isn't executable,
        # even if the umask is set to something that would leave executable bits set.
        # We only run this test on platforms that support umask.
        try:
            old_umask = os.umask(0o077)
            self._box.close()
            os.unlink(self._path)
            self._box = mailbox.mbox(self._path, create=True)
            self._box.add('')
            self._box.close()
        finally:
            os.umask(old_umask)

        st = os.stat(self._path)
        perms = st.st_mode
        self.assertFalse((perms & 0o111)) # Execute bits should all be off. 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:19,代碼來源:test_mailbox.py

示例6: createMessage

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def createMessage(self, dir, mbox=False):
        t = int(time.time() % 1000000)
        pid = self._counter
        self._counter += 1
        filename = ".".join((str(t), str(pid), "myhostname", "mydomain"))
        tmpname = os.path.join(self._dir, "tmp", filename)
        newname = os.path.join(self._dir, dir, filename)
        with open(tmpname, "w") as fp:
            self._msgfiles.append(tmpname)
            if mbox:
                fp.write(FROM_)
            fp.write(DUMMY_MESSAGE)
        if hasattr(os, "link"):
            os.link(tmpname, newname)
        else:
            with open(newname, "w") as fp:
                fp.write(DUMMY_MESSAGE)
        self._msgfiles.append(newname)
        return tmpname 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:21,代碼來源:test_mailbox.py

示例7: ingest

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def ingest(self, file_path):
        mbox = mailbox.mbox(file_path)
        self.result.mime_type = self.DEFAULT_MIME
        self.result.flag(self.result.FLAG_PACKAGE)

        for i, msg in enumerate(mbox.itervalues(), 1):
            # Is there a risk of https://bugs.python.org/issue27321 ?
            msg_path = join_path(self.work_path, '%s.eml' % i)
            try:
                with open(msg_path, 'wb') as fh:
                    fh.write(msg.as_bytes())
            except Exception:
                log.exception("[%s] Cannot extract message %s",
                              self.result, i)
                continue

            child_id = join_path(self.result.id, str(i))
            self.manager.handle_child(self.result,
                                      msg_path,
                                      id=child_id,
                                      mime_type='message/rfc822') 
開發者ID:occrp-attic,項目名稱:ingestors,代碼行數:23,代碼來源:mbox.py

示例8: createMessage

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def createMessage(self, dir, mbox=False):
        t = int(time.time() % 1000000)
        pid = self._counter
        self._counter += 1
        filename = os.extsep.join((str(t), str(pid), "myhostname", "mydomain"))
        tmpname = os.path.join(self._dir, "tmp", filename)
        newname = os.path.join(self._dir, dir, filename)
        fp = open(tmpname, "w")
        self._msgfiles.append(tmpname)
        if mbox:
            fp.write(FROM_)
        fp.write(DUMMY_MESSAGE)
        fp.close()
        if hasattr(os, "link"):
            os.link(tmpname, newname)
        else:
            fp = open(newname, "w")
            fp.write(DUMMY_MESSAGE)
            fp.close()
        self._msgfiles.append(newname)
        return tmpname 
開發者ID:ofermend,項目名稱:medicare-demo,代碼行數:23,代碼來源:test_mailbox.py

示例9: test_generator

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def test_generator(self):
        mail = """Content-Type: text/plain; charset="us-ascii"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nSubject: Scott\'s Laws with a longer subject Scott\'s Laws\nTo: alice@domain.test\nFrom: bob@domain.test\nDate: Sun, 18 Oct 2015 21:45:13 -0000\nX-Tags: \nX-Leap-Encryption: true\nX-Leap-Signature: valid\n\nFirst Law: No matter what goes wrong, it will probably look right. Scott\'s Second Law: When an error has been detected and corrected, it will probably look right. Scott\'s Second Law: When an error has been found in error, it will probably look right. Scott\'s Second Law: When an error has been found in error, it will probably look right. Scott\'s Second Law: When an error has been found in error, it will be impossible to fit the original quantity back into the \n\n First Law: No matter what goes wrong, it will be impossible to fit the original quantity back into the \n\n Scott\'s Second Law: When an error has been found in error, it will be found to have been wrong in the first place. After the correction has been found in error, it will be impossible to fit the original quantity back into the \n\n Second Law: When an error"""
        receiver = 'alice'
        domain_name = 'domain.test'
        mbox_file = pkg_resources.resource_filename('test.unit.fixtures', 'mbox')
        mails = mbox(mbox_file)
        rnd = random.Random(0)

        with patch('pixelated.support.mail_generator.time.time') as time_mock:
            time_mock.return_value = 1446029232.636018

            gen = MailGenerator(receiver, domain_name, mails, rnd)

            result = gen.generate_mail()

            self.assertEqual(mail, result.as_string()) 
開發者ID:pixelated,項目名稱:pixelated-user-agent,代碼行數:18,代碼來源:mail_generator_test.py

示例10: liberate_convert_box

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def liberate_convert_box(result, mail_path, options):
    """ Convert maildir to mbox if needed """
    if options['storage_type'] == '1':
        maildir = mailbox.Maildir(mail_path, factory=None)
        mbox = mailbox.mbox(mail_path + '.mbox')
        mbox.lock()

        for inbox in maildir.list_folders():
            folder = maildir.get_folder(inbox)

            for key in folder.keys():
                msg = folder.pop(key)
                mbox.add(msg)
            maildir.remove_folder(inbox)

        rmtree(mail_path)
        mbox.close()

    return result 
開發者ID:Inboxen,項目名稱:Inboxen,代碼行數:21,代碼來源:tasks.py

示例11: test_download

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def test_download(self):
        url = urls.reverse("download-email-view", kwargs={"email": self.email.eid,
                                                          "inbox": self.email.inbox.inbox,
                                                          "domain": self.email.inbox.domain.domain})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response["Content-Disposition"],
                         "attachment; filename={}-{}.mbox".format(str(self.email.inbox), self.email.eid))
        self.assertEqual(response["Content-Type"], "application/mbox")

        with NamedTemporaryFile() as tmp:
            tmp.write(response.content)
            tmp.file.flush()  # just to be sure

            box = mailbox.mbox(tmp.name)
            self.assertEqual(len(box), 1) 
開發者ID:Inboxen,項目名稱:Inboxen,代碼行數:18,代碼來源:test_email.py

示例12: get_label_id_from_name

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def get_label_id_from_name(service, username, labels, labelname):
  """Get label ID if it already exists, otherwise create it."""
  if labelname.endswith('.mbox'):
    # Strip .mbox suffix from folder names
    labelname = labelname[:-5]
  for label in labels:
    if label['name'].upper() == labelname.upper():
      return label['id']

  logging.info("Label '%s' doesn't exist, creating it", labelname)
  try:
    label_object = {
        'messageListVisibility': 'show',
        'name': labelname,
        'labelListVisibility': 'labelShow'
    }
    label = service.users().labels().create(
        userId=username,
        body=label_object).execute(num_retries=args.num_retries)
    logging.info("Label '%s' created", labelname)
    labels.append(label)
    return label['id']
  except Exception:
    logging.exception("Can't create label '%s' for user %s", labelname, username)
    raise 
開發者ID:google,項目名稱:import-mailbox-to-gmail,代碼行數:27,代碼來源:import-mailbox-to-gmail.py

示例13: fetch

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def fetch(self, category=CATEGORY_MESSAGE, from_date=DEFAULT_DATETIME):
        """Fetch the messages from a set of mbox files.

        The method retrieves, from mbox files, the messages stored in
        these containers.

        :param category: the category of items to fetch
        :param from_date: obtain messages since this date

        :returns: a generator of messages
        """
        if not from_date:
            from_date = DEFAULT_DATETIME

        kwargs = {'from_date': from_date}
        items = super().fetch(category, **kwargs)

        return items 
開發者ID:chaoss,項目名稱:grimoirelab-perceval,代碼行數:20,代碼來源:mbox.py

示例14: parse_mbox

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def parse_mbox(filepath):
        """Parse a mbox file.

        This method parses a mbox file and returns an iterator of dictionaries.
        Each one of this contains an email message.

        :param filepath: path of the mbox to parse

        :returns : generator of messages; each message is stored in a
            dictionary of type `requests.structures.CaseInsensitiveDict`
        """
        mbox = _MBox(filepath, create=False)

        for msg in mbox:
            message = message_to_dict(msg)
            yield message 
開發者ID:chaoss,項目名稱:grimoirelab-perceval,代碼行數:18,代碼來源:mbox.py

示例15: test_reread

# 需要導入模塊: import mailbox [as 別名]
# 或者: from mailbox import mbox [as 別名]
def test_reread(self):
        # Do an initial unconditional refresh
        self._box._refresh()

        # Put the last modified times more than two seconds into the past
        # (because mtime may have only a two second granularity).
        for subdir in ('cur', 'new'):
            os.utime(os.path.join(self._box._path, subdir),
                     (time.time()-5,)*2)

        # Because mtime has a two second granularity in worst case (FAT), a
        # refresh is done unconditionally if called for within
        # two-second-plus-a-bit of the last one, just in case the mbox has
        # changed; so now we have to wait for that interval to expire.
        #
        # Because this is a test, emulate sleeping. Instead of
        # sleeping for 2 seconds, use the skew factor to make _refresh
        # think that 2 seconds have passed and re-reading the _toc is
        # only required if mtimes differ.
        self._box._skewfactor = -3

        # Re-reading causes the ._toc attribute to be assigned a new dictionary
        # object, so we'll check that the ._toc attribute isn't a different
        # object.
        orig_toc = self._box._toc
        def refreshed():
            return self._box._toc is not orig_toc

        self._box._refresh()
        self.assertFalse(refreshed())

        # Now, write something into cur and remove it.  This changes
        # the mtime and should cause a re-read. Note that "sleep
        # emulation" is still in effect, as skewfactor is -3.
        filename = os.path.join(self._path, 'cur', 'stray-file')
        f = open(filename, 'w')
        f.close()
        os.unlink(filename)
        self._box._refresh()
        self.assertTrue(refreshed()) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:42,代碼來源:test_mailbox.py


注:本文中的mailbox.mbox方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。