How to use the offlineimap.OfflineImapError function in offlineimap

To help you get started, we’ve selected a few offlineimap examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github OfflineIMAP / offlineimap / offlineimap / folder / Gmail.py View on Github external
self.ui.collectingdata(None, self)
        imapobj = self.imapserver.acquireconnection()
        try:
            msgsToFetch = self._msgs_to_fetch(
                imapobj, min_date=min_date, min_uid=min_uid)
            if not msgsToFetch:
                return # No messages to sync

            # Get the flags and UIDs for these. single-quotes prevent
            # imaplib2 from quoting the sequence.
            #
            # NB: msgsToFetch are sequential numbers, not UID's
            res_type, response = imapobj.fetch("'%s'"% msgsToFetch,
              '(FLAGS X-GM-LABELS UID)')
            if res_type != 'OK':
                six.reraise(OfflineImapError,
                            OfflineImapError(
                                "FETCHING UIDs in folder [%s]%s failed. "%
                                (self.getrepository(), self) +
                                "Server responded '[%s] %s'"%
                                (res_type, response),
                                OfflineImapError.ERROR.FOLDER),
                            exc_info()[2])
        finally:
            self.imapserver.releaseconnection(imapobj)

        for messagestr in response:
            # looks like: '1 (FLAGS (\\Seen Old) X-GM-LABELS (\\Inbox \\Favorites) UID 4807)' or None if no msg
            # Discard initial message number.
            if messagestr == None:
                continue
            messagestr = messagestr.split(' ', 1)[1]
github OfflineIMAP / offlineimap / offlineimap / folder / Maildir.py View on Github external
# Flags have actually changed, construct new filename Strip
            # off existing infostring
            infomatch = self.re_flagmatch.search(filename)
            if infomatch:
                filename = filename[:-len(infomatch.group())] #strip off
            infostr = '%s2,%s'% (self.infosep, ''.join(sorted(flags)))
            filename += infostr

        newfilename = os.path.join(dir_prefix, filename)
        if (newfilename != oldfilename):
            try:
                os.rename(os.path.join(self.getfullname(), oldfilename),
                          os.path.join(self.getfullname(), newfilename))
            except OSError as e:
                six.reraise(OfflineImapError,
                            OfflineImapError(
                                "Can't rename file '%s' to '%s': %s"%
                                (oldfilename, newfilename, e[1]),
                                OfflineImapError.ERROR.FOLDER),
                            exc_info()[2])

            self.messagelist[uid]['flags'] = flags
            self.messagelist[uid]['filename'] = newfilename
github OfflineIMAP / offlineimap / offlineimap / repository / IMAP.py View on Github external
def makefolder_single(self, foldername):
        self.ui.makefolder(self, foldername)
        if self.account.dryrun:
            return
        imapobj = self.imapserver.acquireconnection()
        try:
            if self.account.utf_8_support:
                foldername = imaputil.utf8_IMAP(foldername)

            result = imapobj.create(foldername)
            if result[0] != 'OK':
                raise OfflineImapError("Folder '%s'[%s] could not be created. "
                    "Server responded: %s"% (foldername, self, str(result)),
                    OfflineImapError.ERROR.FOLDER)
        finally:
            self.imapserver.releaseconnection(imapobj)
github OfflineIMAP / offlineimap / offlineimap / folder / GmailMaildir.py View on Github external
content = self.deletemessageheaders(content, self.labelsheader)
        content = self.addmessageheader(content, '\n', self.labelsheader, labels_str)

        mtime = long(os.stat(filepath).st_mtime)

        # write file with new labels to a unique file in tmp
        messagename = self.new_message_filename(uid, set())
        tmpname = self.save_to_tmp_file(messagename, content)
        tmppath = os.path.join(self.getfullname(), tmpname)

        # move to actual location
        try:
            os.rename(tmppath, filepath)
        except OSError as e:
            raise OfflineImapError("Can't rename file '%s' to '%s': %s" % \
              (tmppath, filepath, e[1]), OfflineImapError.ERROR.FOLDER), \
              None, exc_info()[2]

        # if utime_from_header=true, we don't want to change the mtime.
        if self.utime_from_header and mtime:
            os.utime(filepath, (mtime, mtime))

        # save the new mtime and labels
        self.messagelist[uid]['mtime'] = long(os.stat(filepath).st_mtime)
        self.messagelist[uid]['labels'] = labels
github OfflineIMAP / offlineimap / offlineimap / accounts.py View on Github external
statusfolder = statusrepos.getfolder(remotefolder.getvisiblename().
            replace(remoterepos.getsep(), statusrepos.getsep()))
        statusfolder.openfiles()
        statusfolder.cachemessagelist()

        # Load local folder.
        ui.syncingfolder(remoterepos, remotefolder, localrepos, localfolder)

        # Retrieve messagelists, taking into account age-restriction
        # options.
        maxage = localfolder.getmaxage()
        localstart = localfolder.getstartdate()
        remotestart = remotefolder.getstartdate()
        if (maxage != None) + (localstart != None) + (remotestart != None) > 1:
            six.reraise(OfflineImapError,
                        OfflineImapError("You can set at most one of the "
                            "following: maxage, startdate (for the local "
                            "folder), startdate (for the remote folder)",
                            OfflineImapError.ERROR.REPO),
                        exc_info()[2])
        if (maxage != None or localstart or remotestart) and quick:
            # IMAP quickchanged isn't compatible with options that
            # involve restricting the messagelist, since the "quick"
            # check can only retrieve a full list of UIDs in the folder.
            ui.warn("Quick syncs (-q) not supported in conjunction "
                "with maxage or startdate; ignoring -q.")
        if maxage != None:
            cachemessagelists_upto_date(maxage)
            check_uid_validity()
        elif localstart != None:
            cachemessagelists_startdate(remotefolder, localfolder,
                localstart)
github OfflineIMAP / offlineimap / offlineimap / folder / Maildir.py View on Github external
while tries:
            tries = tries - 1
            try:
                fd = os.open(os.path.join(self.getfullname(), tmpname),
                             os.O_EXCL|os.O_CREAT|os.O_WRONLY, 0o666)
                break
            except OSError as e:
                if not hasattr(e, 'EEXIST'):
                    raise
                if e.errno == e.EEXIST:
                    if tries:
                        time.sleep(0.23)
                        continue
                    severity = OfflineImapError.ERROR.MESSAGE
                    six.reraise(OfflineImapError,
                                OfflineImapError(
                                    "Unique filename %s already exists."%
                                    filename, severity),
                                exc_info()[2])
                else:
                    raise

        fd = os.fdopen(fd, 'wt')
        fd.write(content)
        # Make sure the data hits the disk.
        fd.flush()
        if self.dofsync():
            os.fsync(fd)
        fd.close()

        return tmpname
github OfflineIMAP / offlineimap / offlineimap / folder / UIDMaps.py View on Github external
def _uidlist(self, mapping, items):
        try:
            return [mapping[x] for x in items]
        except KeyError as e:
            six.reraise(OfflineImapError,
                        OfflineImapError(
                            "Could not find UID for msg '{0}' (f:'{1}'."
                            " This is usually a bad thing and should be "
                            "reported on the mailing list.".format(
                                e.args[0], self),
                            OfflineImapError.ERROR.MESSAGE),
                        exc_info()[2])
github OfflineIMAP / offlineimap / offlineimap / accounts.py View on Github external
def __lock(self):
        """Lock the account, throwing an exception if it is locked already."""

        self._lockfd = open(self._lockfilepath, 'w')
        try:
            fcntl.lockf(self._lockfd, fcntl.LOCK_EX|fcntl.LOCK_NB)
        except NameError:
            #fcntl not available (Windows), disable file locking... :(
            pass
        except IOError:
            self._lockfd.close()
            six.reraise(OfflineImapError,
                        OfflineImapError(
                            "Could not lock account %s. Is another "
                            "instance using this account?"% self,
                            OfflineImapError.ERROR.REPO),
                        exc_info()[2])
github OfflineIMAP / offlineimap / offlineimap / folder / GmailMaildir.py View on Github external
# First remove old labels header, and then add the new one
        content = self.deletemessageheaders(content, self.labelsheader)
        content = self.addmessageheader(content, '\n', self.labelsheader, labels_str)

        mtime = long(os.stat(filepath).st_mtime)

        # write file with new labels to a unique file in tmp
        messagename = self.new_message_filename(uid, set())
        tmpname = self.save_to_tmp_file(messagename, content)
        tmppath = os.path.join(self.getfullname(), tmpname)

        # move to actual location
        try:
            os.rename(tmppath, filepath)
        except OSError as e:
            raise OfflineImapError("Can't rename file '%s' to '%s': %s" % \
              (tmppath, filepath, e[1]), OfflineImapError.ERROR.FOLDER), \
              None, exc_info()[2]

        # if utime_from_header=true, we don't want to change the mtime.
        if self.utime_from_header and mtime:
            os.utime(filepath, (mtime, mtime))

        # save the new mtime and labels
        self.messagelist[uid]['mtime'] = long(os.stat(filepath).st_mtime)
        self.messagelist[uid]['labels'] = labels
github OfflineIMAP / offlineimap / offlineimap / repository / IMAP.py View on Github external
xforms = [os.path.expanduser, os.path.expandvars, os.path.abspath]
        cacertfile = self.getconf_xform('sslcacertfile', xforms, None)
        # Can't use above cacertfile because of abspath.
        if self.getconf('sslcacertfile', None) == "OS-DEFAULT":
            cacertfile = get_os_sslcertfile()
            if cacertfile == None:
                searchpath = get_os_sslcertfile_searchpath()
                if searchpath:
                    reason = "Default CA bundle was requested, "\
                             "but no existing locations available.  "\
                             "Tried %s." % (", ".join(searchpath))
                else:
                    reason = "Default CA bundle was requested, "\
                             "but OfflineIMAP doesn't know any for your "\
                             "current operating system."
                raise OfflineImapError(reason, OfflineImapError.ERROR.REPO)
        if cacertfile is None:
            return None
        if not os.path.isfile(cacertfile):
            reason = "CA certfile for repository '%s' couldn't be found.  "\
                     "No such file: '%s'" % (self.name, cacertfile)
            raise OfflineImapError(reason, OfflineImapError.ERROR.REPO)
        return cacertfile