Login

Get email and push on couchdb - utils

Author:
magik_cypress
Posted:
March 1, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

Check email and save

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
import mailbox, imaplib, re, email
from mailreactor.app import markup, MailArchive

class ImapCheck:
  def __init__(self):
      self.IMAP_SERVER='IP.IP.IP.IP'
      self.IMAP_PORT=993
      self.M = None
      self.response = None
      self.mailboxes = []

  def login(self, username, password):
      self.M = imaplib.IMAP4_SSL(self.IMAP_SERVER, self.IMAP_PORT)
      rc, self.response = self.M.login(username, password)
      return rc

  def logout(self):
      self.M.logout()

  def content_email(self, num):
      """ Email header
      """
      self.head = []
      typ, msg_data = self.M.fetch(num, '(BODY.PEEK[HEADER])')
      for response_part in msg_data:
          if isinstance(response_part, tuple):
              self.header_view = response_part[1]
              msg = email.message_from_string(response_part[1])
              for header in [ 'subject', 'to', 'from', 'date', 'Message-ID']:
                  self.head.append(msg[header])

      """ Email content
      """
      self.messagePlainText = ''
      self.messageHTML = ''
      self.messageAttachments = []
      typ, msg_data = self.M.fetch(num, '(RFC822)')
      for response_part in msg_data:
          if isinstance(response_part, tuple):
              self.body = response_part[1]
              msg = email.message_from_string(response_part[1])
              for part in msg.walk():   #http://docs.python.org/library/email.message.html
                if str(part.get_content_type()) == 'text/plain':
                    self.messagePlainText = self.messagePlainText + str(part.get_payload())
                if str(part.get_content_type()) == 'text/html':
                    self.messageHTML = self.messageHTML + str(part.get_payload())
                if part.get_filename():
                    self.messageAttachments.append((part.get_filename(), part.get_payload(decode=true)))

      """ Email flag
      """
      typ, msg_data = self.M.fetch(num, '(FLAGS)')
      for response_part in msg_data:
          self.flag = imaplib.ParseFlags(response_part)

      context = {
        'header_view': self.header_view,
        'head': self.head,
        'body': self.body,
        'messagePlainText': self.messagePlainText,
        'messageHTML': self.messageHTML,
        'messageAttachments': self.messageAttachments,
        'flag': self.flag,
      }
      return context

  def get_mails(self, folder='INBOX'):
      status, count = self.M.select(folder, readonly=1)
      status, response = self.M.search('UTF-8', 'Unseen')
      for num in response[0].split():
            entry = MailArchive()
            data = self.content_email(num)

            import uuid
            entry['_id'] = unicode(uuid.uuid4())

            entry['header'] = unicode(data['header_view'])
            entry['head_subject'] = unicode(data['head'][0])
            entry['head_to'] = unicode(data['head'][1])
            entry['head_from'] = unicode(data['head'][2])
            entry['head_date'] = unicode(data['head'][3])
            entry['message_id'] = unicode(data['head'][4])

            entry['body'] = markup(unicode(data['body']), escape=True, small_headings=False)
            entry['body_text'] = unicode(data['messagePlainText'])
            entry['body_html'] = unicode(data['messageHTML'])

            entry['flag'] = unicode(data['flag'][0])

            entry.save()

            doc = data['messageAttachments']
            for k, v in doc:
                entry.put_attachment(v, unicode(k))


            typ, response = self.M.store(num, '+FLAGS', '\Seen')

      return

def read_mailbox():
    entry = MailArchive()
    c = ImapCheck()
    c.login('[email protected]', 'passwd')
    email = c.get_mails()
    c.logout()

    return email

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.