Exemplo n.º 1
0
 def getUidList(self, new_only, date_filter=None):
     try:
         if None != date_filter:
             filter = 'SENTSINCE %s' % date_filter.strftime("%d-%b-%Y")
         else:
             filter = None
         if new_only:
             type_uid = 'UNSEEN'
         else:
             type_uid = 'ALL'
         # Получение данных в зависимости от фильтров
         (status, data) = self.mail.uid('search', None, filter, type_uid)
         # Проверка успешности получение данных
         if 'OK' != status:
             raise exlite.ExceptionLite('Status: %s' % (status))
         # Конвертируем данные
         uid_test = str(data[0], 'utf8')
         if '' == uid_test:
             return list()
         else:
             return str(data[0], 'utf8').split(' ')
     # Перехват ошибок "транспорта"(socket)
     except socket_error as s:
         raise exlite.ExceptionLite('(Socket) ' +
                                    self.__bytesToStr__(s.args[1]))
     # Перехват ошибок IMAP
     except imaplib.IMAP4.error as i:
         raise exlite.ExceptionLite('(IMAP)' +
                                    self.__bytesToStr__(i.args[0]))
Exemplo n.º 2
0
 def __syncFolders__(self):
     try:
         # Получение данных с сервера
         (status, data) = self.mail.list()
         # Проверка статуса
         if 'OK' != status:
             raise exlite.ExceptionLite('status: ' + status)
         # Псевдонимы каталогов для коректного поиска и отображения
         dic_folders = {
             'inbox': 'Входящие',
             'important': 'Важные',
             'drafts': 'Черновики',
             'draftbox': 'Черновики',
             'sent': 'Отправленные',
             'sentbox': 'Отправленные',
             'flagged': 'Помеченные',
             'trash': 'Корзина',
             'junk': 'Спам',
             'spam': 'Спам'
         }
         # Список для очистки от неиспользуемых данных
         replace_flag_list = ('\HasNoChildren', '\HasChildren', 'Noselect',
                              'All', 'Unmarked', '\\', '"', ' ')
         # Регулярное выражение для разбивки данных с сервера
         re_pattern = re.compile(
             r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" (?P<name>.*)')
         self.folders = {}
         # Проход в цикле по всем строкам полученных с сервера
         for line in data:
             # Разбиваем согласно регулярки
             match = re_pattern.match(str(line, 'utf-8'))
             # Групируем
             (flags, delimiter, name) = match.groups()
             # Убираем кавычки и неиспользуемые элементы
             for replace_str in replace_flag_list:
                 flags = flags.replace(replace_str, '')
                 name = name.replace(replace_str, '')
             # Поиск имени пакпки в словаре
             if name.lower() in dic_folders:
                 flags = dic_folders[name.lower()]
             else:
                 # Если в словаре нет пробуем декодировать из Base64
                 re_patern = re.compile('&(\S+)-')
                 rlist = re.findall(re_patern, name)
                 if 0 < len(rlist):
                     flags = self.__decodeB64toStr__(rlist[0], 'utf-16BE')
             if '' != flags:
                 self.folders[flags] = name
     # Перехват ошибок "транспорта"
     except socket_error as s:
         raise exlite.ExceptionLite('(Socket) ' +
                                    self.__bytesToStr__(s.args[1]))
     # Перехват ошибок IMAP
     except imaplib.IMAP4.error as i:
         raise exlite.ExceptionLite('(IMAP)' +
                                    self.__bytesToStr__(i.args[0]))
Exemplo n.º 3
0
 def __init__(self, config):
     try:
         # Подключаемся к хосту
         self.mail = imaplib.IMAP4_SSL(config.host, config.port)
         # Авторизация
         self.mail.login(config.login, config.password)
         # Обновление списка папок IMAP
         self.__syncFolders__()
     # Перехват ошибок "транспорта"(socket)
     except socket_error as s:
         raise exlite.ExceptionLite('(Socket) ' +
                                    self.__bytesToStr__(s.args[1]))
     # Перехват ошибок IMAP
     except imaplib.IMAP4.error as i:
         raise exlite.ExceptionLite('(IMAP)' +
                                    self.__bytesToStr__(i.args[0]))
Exemplo n.º 4
0
 def deleteMessage(self, uid):
     try:
         folder_trash = self.folders['Корзина']
         self.mail.uid('STORE', uid, '+FLAGS', '(\\Deleted)')
         self.mail.expunge()
     # Перехват ошибок ввода
     except KeyError as ke:
         raise exlite.ExceptionLite('Folder not found: <%s>' % ke.args[0])
     # Перехват ошибок "транспорта"(socket)
     except socket_error as s:
         raise exlite.ExceptionLite('(Socket) ' +
                                    self.__bytesToStr__(s.args[1]))
     # Перехват ошибок IMAP
     except imaplib.IMAP4.error as i:
         raise exlite.ExceptionLite('(IMAP)' +
                                    self.__bytesToStr__(i.args[0]))
Exemplo n.º 5
0
 def setFolder(self, folder):
     try:
         (status, data) = self.mail.select(self.folders[folder])
         if 'OK' != status:
             raise exlite.ExceptionLite('status: ' + status)
     # Перехват ошибок ввода
     except KeyError as ke:
         raise exlite.ExceptionLite('Folder not found: <%s>' % folder)
     # Перехват ошибок "транспорта"(socket)
     except socket_error as s:
         raise exlite.ExceptionLite('(Socket) ' +
                                    self.__bytesToStr__(s.args[1]))
     # Перехват ошибок IMAP
     except imaplib.IMAP4.error as i:
         raise exlite.ExceptionLite('(IMAP)' +
                                    self.__bytesToStr__(i.args[0]))
Exemplo n.º 6
0
 def getMessageData(self, uid):
     try:
         (status, data) = self.mail.uid('fetch', str(uid), '(RFC822)')
         # Проверка успешности получение данных
         if "OK" != status:
             raise exlite.ExceptionLite("Massage not found")
         # Конвертируем данные из bytes в Message
         msg = email.message_from_bytes(data[0][1])
         # Получаем "отправителя"
         address_from = self.__decodeAddress__(msg["From"])
         # Получаем список "получателей"
         address_to = self.__decodeAddress__(msg["To"])
         # Получаем список "в копии"
         address_cc = self.__decodeAddress__(msg["Cc"])
         # Дата и время отправки сообщения
         date_time = self.__decodeTimestamp__(
             email.utils.parsedate_tz(msg['date']))
         # Тема письма
         subject = self.__decodeImapStr__(msg["subject"])
         # Тело письма и вложение(я)
         body_plain = ''
         body_html = ''
         attachment = {}
         if msg.is_multipart():
             for part in msg.walk():
                 content_type = part.get_content_type()
                 content_disposition = str(part.get('Content-Disposition'))
                 content_charset = part.get_content_charset()
                 if None == content_charset:
                     content_charset = 'utf-8'
                 if 'attachment' not in content_disposition:
                     if 'text/plain' == content_type:
                         body_plain = part.get_payload(
                             decode=True).decode(content_charset)
                     elif 'text/html' == content_type:
                         body_html = part.get_payload(
                             decode=True).decode(content_charset)
                 else:
                     filename = self.__decodeImapStr__(part.get_filename())
                     attachment[filename] = part.get_payload(decode=True)
         else:
             content_type = msg.get_content_type()
             content_disposition = str(msg.get("Content-Disposition"))
             content_charset = msg.get_content_charset()
             if None == content_charset:
                 content_charset = 'utf-8'
             if 'attachment' not in content_disposition:
                 if 'text/plain' == content_type:
                     body_plain = msg.get_payload(
                         decode=True).decode(content_charset)
                 elif 'text/html' == content_type:
                     body_html = msg.get_payload(
                         decode=True).decode(content_charset)
             else:
                 filename = self.__decodeImapStr__(msg.get_filename())
                 attachment[filename] = msg.get_payload(decode=True)
         # Возврат сообщения
         return MessageData(address_from, address_to, address_cc, subject,
                            body_plain, body_html, date_time, attachment)
     # Перехват ошибок "транспорта"(socket)
     except socket_error as s:
         raise exlite.ExceptionLite('(Socket) ' +
                                    self.__bytesToStr__(s.args[1]))
     # Перехват ошибок IMAP
     except imaplib.IMAP4.error as i:
         raise exlite.ExceptionLite('(IMAP)' +
                                    self.__bytesToStr__(i.args[0]))