You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

179 lines
5.2 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. from __future__ import unicode_literals
  23. from webnotes.utils import extract_email_id, convert_utc_to_user_timezone
  24. class IncomingMail:
  25. """
  26. Single incoming email object. Extracts, text / html and attachments from the email
  27. """
  28. def __init__(self, content):
  29. import email
  30. import time
  31. import datetime
  32. import email.utils
  33. self.mail = email.message_from_string(content)
  34. self.text_content = ''
  35. self.html_content = ''
  36. self.attachments = []
  37. self.parse()
  38. self.set_content_and_type()
  39. self.from_email = extract_email_id(self.mail["From"])
  40. self.from_real_name = email.utils(self.mail["From"])[0]
  41. utc = email.utils.mktime_tz(email.utils.parsedate_tz(self.mail["Date"]))
  42. self.date = convert_utc_to_user_timezone(utc).strftime('%Y-%m-%d %H:%M:%S')
  43. def parse(self):
  44. for part in self.mail.walk():
  45. self.process_part(part)
  46. def set_content_and_type(self):
  47. self.content, self.content_type = '[Blank Email]', 'text/plain'
  48. if self.text_content:
  49. self.content, self.content_type = self.text_content, 'text/plain'
  50. else:
  51. self.content, self.content_type = self.html_content, 'text/html'
  52. def process_part(self, part):
  53. content_type = part.get_content_type()
  54. charset = part.get_content_charset()
  55. if not charset: charset = self.get_charset(part)
  56. if content_type == 'text/plain':
  57. self.text_content += self.get_payload(part, charset)
  58. if content_type == 'text/html':
  59. self.html_content += self.get_payload(part, charset)
  60. if part.get_filename():
  61. self.get_attachment(part, charset)
  62. def get_text_content(self):
  63. return self.text_content or self.html_content
  64. def get_charset(self, part):
  65. charset = part.get_content_charset()
  66. if not charset:
  67. import chardet
  68. charset = chardet.detect(str(part))['encoding']
  69. return charset
  70. def get_payload(self, part, charset):
  71. try:
  72. return unicode(part.get_payload(decode=True),str(charset),"ignore")
  73. except LookupError, e:
  74. return part.get_payload()
  75. def get_attachment(self, part, charset):
  76. self.attachments.append({
  77. 'content-type': part.get_content_type(),
  78. 'filename': part.get_filename(),
  79. 'content': part.get_payload(decode=True),
  80. })
  81. def save_attachments_in_doc(self, doc):
  82. from webnotes.utils.file_manager import save_file, add_file_list
  83. for attachment in self.attachments:
  84. fid = save_file(attachment['filename'], attachment['content'])
  85. status = add_file_list(doc.doctype, doc.name, fid, fid)
  86. def get_thread_id(self):
  87. import re
  88. subject = self.mail.get('Subject', '')
  89. l= re.findall('(?<=\[)[\w/-]+', subject)
  90. return l and l[0] or None
  91. class POP3Mailbox:
  92. def __init__(self, args=None):
  93. self.setup(args)
  94. self.get_messages()
  95. def setup(self, args=None):
  96. # overrride
  97. import webnotes
  98. self.settings = args or webnotes._dict()
  99. def check_mails(self):
  100. # overrride
  101. return True
  102. def process_message(self, mail):
  103. # overrride
  104. pass
  105. def connect(self):
  106. import poplib
  107. if self.settings.use_ssl:
  108. self.pop = poplib.POP3_SSL(self.settings.host)
  109. else:
  110. self.pop = poplib.POP3(self.settings.host)
  111. self.pop.user(self.settings.username)
  112. self.pop.pass_(self.settings.password)
  113. def get_messages(self):
  114. import webnotes
  115. if not self.check_mails():
  116. return # nothing to do
  117. webnotes.conn.commit()
  118. self.connect()
  119. num = num_copy = len(self.pop.list()[1])
  120. # track if errors arised
  121. errors = False
  122. # WARNING: Hard coded max no. of messages to be popped
  123. if num > 20: num = 20
  124. for m in xrange(1, num+1):
  125. msg = self.pop.retr(m)
  126. self.pop.dele(m)
  127. try:
  128. incoming_mail = IncomingMail(b'\n'.join(msg[1]))
  129. webnotes.conn.begin()
  130. self.process_message(incoming_mail)
  131. webnotes.conn.commit()
  132. except:
  133. from webnotes.utils.scheduler import log
  134. # log performs rollback and logs error in scheduler log
  135. log("receive.get_messages")
  136. errors = True
  137. webnotes.conn.rollback()
  138. # WARNING: Delete message number 101 onwards from the pop list
  139. # This is to avoid having too many messages entering the system
  140. num = num_copy
  141. if num > 100 and not errors:
  142. for m in xrange(101, num+1):
  143. self.pop.dele(m)
  144. self.pop.quit()
  145. webnotes.conn.begin()