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.
 
 
 
 
 
 

572 regels
16 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import time, _socket, poplib, imaplib, email, email.utils, datetime, chardet, re, hashlib
  5. from email_reply_parser import EmailReplyParser
  6. from email.header import decode_header
  7. import frappe
  8. from frappe import _
  9. from frappe.utils import (extract_email_id, convert_utc_to_user_timezone, now,
  10. cint, cstr, strip, markdown)
  11. from frappe.utils.scheduler import log
  12. from frappe.utils.file_manager import get_random_filename, save_file, MaxFileSizeReachedError
  13. import re
  14. class EmailSizeExceededError(frappe.ValidationError): pass
  15. class EmailTimeoutError(frappe.ValidationError): pass
  16. class TotalSizeExceededError(frappe.ValidationError): pass
  17. class LoginLimitExceeded(frappe.ValidationError): pass
  18. class EmailServer:
  19. """Wrapper for POP server to pull emails."""
  20. def __init__(self, args=None):
  21. self.setup(args)
  22. def setup(self, args=None):
  23. # overrride
  24. self.settings = args or frappe._dict()
  25. def check_mails(self):
  26. # overrride
  27. return True
  28. def process_message(self, mail):
  29. # overrride
  30. pass
  31. def connect(self):
  32. """Connect to **Email Account**."""
  33. if cint(self.settings.use_imap):
  34. return self.connect_imap()
  35. else:
  36. return self.connect_pop()
  37. def connect_imap(self):
  38. """Connect to IMAP"""
  39. try:
  40. if cint(self.settings.use_ssl):
  41. self.imap = Timed_IMAP4_SSL(self.settings.host, timeout=frappe.conf.get("pop_timeout"))
  42. else:
  43. self.imap = Timed_IMAP4(self.settings.host, timeout=frappe.conf.get("pop_timeout"))
  44. self.imap.login(self.settings.username, self.settings.password)
  45. # connection established!
  46. return True
  47. except _socket.error:
  48. # Invalid mail server -- due to refusing connection
  49. frappe.msgprint(_('Invalid Mail Server. Please rectify and try again.'))
  50. raise
  51. except Exception, e:
  52. frappe.msgprint(_('Cannot connect: {0}').format(str(e)))
  53. raise
  54. def connect_pop(self):
  55. #this method return pop connection
  56. try:
  57. if cint(self.settings.use_ssl):
  58. self.pop = Timed_POP3_SSL(self.settings.host, timeout=frappe.conf.get("pop_timeout"))
  59. else:
  60. self.pop = Timed_POP3(self.settings.host, timeout=frappe.conf.get("pop_timeout"))
  61. self.pop.user(self.settings.username)
  62. self.pop.pass_(self.settings.password)
  63. # connection established!
  64. return True
  65. except _socket.error:
  66. # log performs rollback and logs error in Error Log
  67. log("receive.connect_pop")
  68. # Invalid mail server -- due to refusing connection
  69. frappe.msgprint(_('Invalid Mail Server. Please rectify and try again.'))
  70. raise
  71. except poplib.error_proto, e:
  72. if self.is_temporary_system_problem(e):
  73. return False
  74. else:
  75. frappe.msgprint(_('Invalid User Name or Support Password. Please rectify and try again.'))
  76. raise
  77. def get_messages(self):
  78. """Returns new email messages in a list."""
  79. if not self.check_mails():
  80. return # nothing to do
  81. frappe.db.commit()
  82. if not self.connect():
  83. return
  84. uid_list = []
  85. try:
  86. # track if errors arised
  87. self.errors = False
  88. self.latest_messages = []
  89. self.seen_status = {}
  90. self.uid_reindexed = False
  91. uid_list = email_list = self.get_new_mails()
  92. if not email_list:
  93. return
  94. num = num_copy = len(email_list)
  95. # WARNING: Hard coded max no. of messages to be popped
  96. if num > 50: num = 50
  97. # size limits
  98. self.total_size = 0
  99. self.max_email_size = cint(frappe.local.conf.get("max_email_size"))
  100. self.max_total_size = 5 * self.max_email_size
  101. for i, message_meta in enumerate(email_list):
  102. # do not pull more than NUM emails
  103. if (i+1) > num:
  104. break
  105. try:
  106. self.retrieve_message(message_meta, i+1)
  107. except (TotalSizeExceededError, EmailTimeoutError, LoginLimitExceeded):
  108. break
  109. # WARNING: Mark as read - message number 101 onwards from the pop list
  110. # This is to avoid having too many messages entering the system
  111. num = num_copy
  112. if not cint(self.settings.use_imap):
  113. if num > 100 and not self.errors:
  114. for m in xrange(101, num+1):
  115. self.pop.dele(m)
  116. except Exception, e:
  117. if self.has_login_limit_exceeded(e):
  118. pass
  119. else:
  120. raise
  121. finally:
  122. # no matter the exception, pop should quit if connected
  123. if cint(self.settings.use_imap):
  124. self.imap.logout()
  125. else:
  126. self.pop.quit()
  127. out = { "latest_messages": self.latest_messages }
  128. if self.settings.use_imap:
  129. out.update({
  130. "uid_list": uid_list,
  131. "seen_status": self.seen_status,
  132. "uid_reindexed": self.uid_reindexed
  133. })
  134. return out
  135. def get_new_mails(self):
  136. """Return list of new mails"""
  137. if cint(self.settings.use_imap):
  138. email_list = []
  139. self.check_imap_uidvalidity()
  140. self.imap.select("Inbox", readonly=False)
  141. response, message = self.imap.uid('search', None, self.settings.email_sync_rule)
  142. if message[0]:
  143. email_list = message[0].split()
  144. else:
  145. email_list = self.pop.list()[1]
  146. return email_list
  147. def check_imap_uidvalidity(self):
  148. # compare the UIDVALIDITY of email account and imap server
  149. uid_validity = self.settings.uid_validity
  150. responce, message = self.imap.status("Inbox", "(UIDVALIDITY UIDNEXT)")
  151. current_uid_validity = self.parse_imap_responce("UIDVALIDITY", message[0])
  152. if not current_uid_validity:
  153. frappe.throw(_("Can not find UIDVALIDITY in imap status response"))
  154. uidnext = int(self.parse_imap_responce("UIDNEXT", message[0]) or "1")
  155. frappe.db.set_value("Email Account", self.settings.email_account, "uidnext", uidnext)
  156. if not uid_validity or uid_validity != current_uid_validity:
  157. # uidvalidity changed & all email uids are reindexed by server
  158. frappe.db.sql("""update `tabCommunication` set uid=-1 where communication_medium='Email'
  159. and email_account='{email_account}'""".format(email_account=self.settings.email_account))
  160. frappe.db.sql("""update `tabEmail Account` set uidvalidity='{uidvalidity}', uidnext={uidnext} where
  161. name='{email_account}'""".format(
  162. uidvalidity=current_uid_validity,
  163. uidnext=uidnext,
  164. email_account=self.settings.email_account)
  165. )
  166. # uid validity not found pulling emails for first time
  167. if not uid_validity:
  168. self.settings.email_sync_rule = "UNSEEN"
  169. return
  170. sync_count = 100 if uid_validity else int(self.settings.initial_sync_count)
  171. from_uid = 1 if uidnext < (sync_count + 1) or (uidnext - sync_count) < 1 else uidnext - sync_count
  172. # sync last 100 email
  173. self.settings.email_sync_rule = "UID {}:{}".format(from_uid, uidnext)
  174. self.uid_reindexed = True
  175. elif uid_validity == current_uid_validity:
  176. return
  177. def parse_imap_responce(self, cmd, responce):
  178. pattern = r"(?<={cmd} )[0-9]*".format(cmd=cmd)
  179. match = re.search(pattern, responce, re.U | re.I)
  180. if match:
  181. return match.group(0)
  182. else:
  183. return None
  184. def retrieve_message(self, message_meta, msg_num=None):
  185. incoming_mail = None
  186. try:
  187. self.validate_message_limits(message_meta)
  188. if cint(self.settings.use_imap):
  189. status, message = self.imap.uid('fetch', message_meta, '(BODY.PEEK[] BODY.PEEK[HEADER] FLAGS)')
  190. raw, header, ignore = message
  191. self.get_email_seen_status(message_meta, raw[0])
  192. self.latest_messages.append(raw[1])
  193. else:
  194. msg = self.pop.retr(msg_num)
  195. self.latest_messages.append(b'\n'.join(msg[1]))
  196. except (TotalSizeExceededError, EmailTimeoutError):
  197. # propagate this error to break the loop
  198. self.errors = True
  199. raise
  200. except Exception, e:
  201. if self.has_login_limit_exceeded(e):
  202. self.errors = True
  203. raise LoginLimitExceeded, e
  204. else:
  205. # log performs rollback and logs error in Error Log
  206. log("receive.get_messages", self.make_error_msg(msg_num, incoming_mail))
  207. self.errors = True
  208. frappe.db.rollback()
  209. if not cint(self.settings.use_imap):
  210. self.pop.dele(msg_num)
  211. else:
  212. # mark as seen
  213. self.imap.uid('STORE', message_meta, '+FLAGS', '(\\SEEN)')
  214. else:
  215. if not cint(self.settings.use_imap):
  216. self.pop.dele(msg_num)
  217. else:
  218. # mark as seen
  219. self.imap.uid('STORE', message_meta, '+FLAGS', '(\\SEEN)')
  220. def get_email_seen_status(self, uid, flag_string):
  221. """ parse the email FLAGS response """
  222. if not flag_string:
  223. return None
  224. flags = []
  225. for flag in imaplib.ParseFlags(flag_string) or []:
  226. pattern = re.compile("\w+")
  227. match = re.search(pattern, flag)
  228. flags.append(match.group(0))
  229. if "Seen" in flags:
  230. self.seen_status.update({ uid: "SEEN" })
  231. else:
  232. self.seen_status.update({ uid: "UNSEEN" })
  233. def has_login_limit_exceeded(self, e):
  234. return "-ERR Exceeded the login limit" in strip(cstr(e.message))
  235. def is_temporary_system_problem(self, e):
  236. messages = (
  237. "-ERR [SYS/TEMP] Temporary system problem. Please try again later.",
  238. "Connection timed out",
  239. )
  240. for message in messages:
  241. if message in strip(cstr(e.message)) or message in strip(cstr(getattr(e, 'strerror', ''))):
  242. return True
  243. return False
  244. def validate_message_limits(self, message_meta):
  245. # throttle based on email size
  246. if not self.max_email_size:
  247. return
  248. m, size = message_meta.split()
  249. size = cint(size)
  250. if size < self.max_email_size:
  251. self.total_size += size
  252. if self.total_size > self.max_total_size:
  253. raise TotalSizeExceededError
  254. else:
  255. raise EmailSizeExceededError
  256. def make_error_msg(self, msg_num, incoming_mail):
  257. error_msg = "Error in retrieving email."
  258. if not incoming_mail:
  259. try:
  260. # retrieve headers
  261. incoming_mail = Email(b'\n'.join(self.pop.top(msg_num, 5)[1]))
  262. except:
  263. pass
  264. if incoming_mail:
  265. error_msg += "\nDate: {date}\nFrom: {from_email}\nSubject: {subject}\n".format(
  266. date=incoming_mail.date, from_email=incoming_mail.from_email, subject=incoming_mail.subject)
  267. return error_msg
  268. def update_flag(self, uid_list={}):
  269. """ set all uids mails the flag as seen """
  270. if not uid_list:
  271. return
  272. if not self.connect():
  273. return
  274. self.imap.select("Inbox")
  275. for uid, operation in uid_list.iteritems():
  276. if not uid: continue
  277. op = "+FLAGS" if operation == "Read" else "-FLAGS"
  278. try:
  279. self.imap.uid('STORE', uid, op, '(\\SEEN)')
  280. except Exception as e:
  281. continue
  282. class Email:
  283. """Wrapper for an email."""
  284. def __init__(self, content):
  285. """Parses headers, content, attachments from given raw message.
  286. :param content: Raw message."""
  287. self.raw = content
  288. self.mail = email.message_from_string(self.raw)
  289. self.text_content = ''
  290. self.html_content = ''
  291. self.attachments = []
  292. self.cid_map = {}
  293. self.parse()
  294. self.set_content_and_type()
  295. self.set_subject()
  296. self.set_from()
  297. self.message_id = (self.mail.get('Message-ID') or "").strip(" <>")
  298. if self.mail["Date"]:
  299. try:
  300. utc = email.utils.mktime_tz(email.utils.parsedate_tz(self.mail["Date"]))
  301. utc_dt = datetime.datetime.utcfromtimestamp(utc)
  302. self.date = convert_utc_to_user_timezone(utc_dt).strftime('%Y-%m-%d %H:%M:%S')
  303. except:
  304. self.date = now()
  305. else:
  306. self.date = now()
  307. if self.date > now():
  308. self.date = now()
  309. def parse(self):
  310. """Walk and process multi-part email."""
  311. for part in self.mail.walk():
  312. self.process_part(part)
  313. def set_subject(self):
  314. """Parse and decode `Subject` header."""
  315. _subject = decode_header(self.mail.get("Subject", "No Subject"))
  316. self.subject = _subject[0][0] or ""
  317. if _subject[0][1]:
  318. self.subject = self.subject.decode(_subject[0][1])
  319. else:
  320. # assume that the encoding is utf-8
  321. self.subject = self.subject.decode("utf-8")[:140]
  322. if not self.subject:
  323. self.subject = "No Subject"
  324. def set_from(self):
  325. # gmail mailing-list compatibility
  326. # use X-Original-Sender if available, as gmail sometimes modifies the 'From'
  327. _from_email = self.decode_email(self.mail.get("X-Original-From") or self.mail["From"])
  328. _reply_to = self.decode_email(self.mail.get("Reply-To"))
  329. if _reply_to and not frappe.db.get_value('Email Account', {"email_id":_reply_to}, 'email_id'):
  330. self.from_email = extract_email_id(_reply_to)
  331. else:
  332. self.from_email = extract_email_id(_from_email)
  333. if self.from_email:
  334. self.from_email = self.from_email.lower()
  335. self.from_real_name = email.utils.parseaddr(_from_email)[0] if "@" in _from_email else _from_email
  336. def decode_email(self, email):
  337. if not email: return
  338. decoded = ""
  339. for part, encoding in decode_header(frappe.as_unicode(email).replace("\""," ").replace("\'"," ")):
  340. if encoding:
  341. decoded += part.decode(encoding)
  342. else:
  343. decoded += part.decode('utf-8')
  344. return decoded
  345. def set_content_and_type(self):
  346. self.content, self.content_type = '[Blank Email]', 'text/plain'
  347. if self.html_content:
  348. self.content, self.content_type = self.html_content, 'text/html'
  349. else:
  350. self.content, self.content_type = EmailReplyParser.read(self.text_content).text.replace("\n","\n\n"), 'text/plain'
  351. def process_part(self, part):
  352. """Parse email `part` and set it to `text_content`, `html_content` or `attachments`."""
  353. content_type = part.get_content_type()
  354. if content_type == 'text/plain':
  355. self.text_content += self.get_payload(part)
  356. elif content_type == 'text/html':
  357. self.html_content += self.get_payload(part)
  358. elif content_type == 'message/rfc822':
  359. # sent by outlook when another email is sent as an attachment to this email
  360. self.show_attached_email_headers_in_content(part)
  361. elif part.get_filename() or 'image' in content_type:
  362. self.get_attachment(part)
  363. def show_attached_email_headers_in_content(self, part):
  364. # get the multipart/alternative message
  365. message = list(part.walk())[1]
  366. headers = []
  367. for key in ('From', 'To', 'Subject', 'Date'):
  368. value = cstr(message.get(key))
  369. if value:
  370. headers.append('{label}: {value}'.format(label=_(key), value=value))
  371. self.text_content += '\n'.join(headers)
  372. self.html_content += '<hr>' + '\n'.join('<p>{0}</p>'.format(h) for h in headers)
  373. if not message.is_multipart() and message.get_content_type()=='text/plain':
  374. # email.parser didn't parse it!
  375. text_content = self.get_payload(message)
  376. self.text_content += text_content
  377. self.html_content += markdown(text_content)
  378. def get_charset(self, part):
  379. """Detect chartset."""
  380. charset = part.get_content_charset()
  381. if not charset:
  382. charset = chardet.detect(str(part))['encoding']
  383. return charset
  384. def get_payload(self, part):
  385. charset = self.get_charset(part)
  386. try:
  387. return unicode(part.get_payload(decode=True), str(charset), "ignore")
  388. except LookupError:
  389. return part.get_payload()
  390. def get_attachment(self, part):
  391. #charset = self.get_charset(part)
  392. fcontent = part.get_payload(decode=True)
  393. if fcontent:
  394. content_type = part.get_content_type()
  395. fname = part.get_filename()
  396. if fname:
  397. try:
  398. fname = fname.replace('\n', ' ').replace('\r', '')
  399. fname = cstr(decode_header(fname)[0][0])
  400. except:
  401. fname = get_random_filename(content_type=content_type)
  402. else:
  403. fname = get_random_filename(content_type=content_type)
  404. self.attachments.append({
  405. 'content_type': content_type,
  406. 'fname': fname,
  407. 'fcontent': fcontent,
  408. })
  409. cid = (part.get("Content-Id") or "").strip("><")
  410. if cid:
  411. self.cid_map[fname] = cid
  412. def save_attachments_in_doc(self, doc):
  413. """Save email attachments in given document."""
  414. saved_attachments = []
  415. for attachment in self.attachments:
  416. try:
  417. file_data = save_file(attachment['fname'], attachment['fcontent'],
  418. doc.doctype, doc.name, is_private=1)
  419. saved_attachments.append(file_data)
  420. if attachment['fname'] in self.cid_map:
  421. self.cid_map[file_data.name] = self.cid_map[attachment['fname']]
  422. except MaxFileSizeReachedError:
  423. # WARNING: bypass max file size exception
  424. pass
  425. except frappe.DuplicateEntryError:
  426. # same file attached twice??
  427. pass
  428. return saved_attachments
  429. def get_thread_id(self):
  430. """Extract thread ID from `[]`"""
  431. l = re.findall('(?<=\[)[\w/-]+', self.subject)
  432. return l and l[0] or None
  433. # fix due to a python bug in poplib that limits it to 2048
  434. poplib._MAXLINE = 20480
  435. class TimerMixin(object):
  436. def __init__(self, *args, **kwargs):
  437. self.timeout = kwargs.pop('timeout', 0.0)
  438. self.elapsed_time = 0.0
  439. self._super.__init__(self, *args, **kwargs)
  440. if self.timeout:
  441. # set per operation timeout to one-fifth of total pop timeout
  442. self.sock.settimeout(self.timeout / 5.0)
  443. def _getline(self, *args, **kwargs):
  444. start_time = time.time()
  445. ret = self._super._getline(self, *args, **kwargs)
  446. self.elapsed_time += time.time() - start_time
  447. if self.timeout and self.elapsed_time > self.timeout:
  448. raise EmailTimeoutError
  449. return ret
  450. def quit(self, *args, **kwargs):
  451. self.elapsed_time = 0.0
  452. return self._super.quit(self, *args, **kwargs)
  453. class Timed_POP3(TimerMixin, poplib.POP3):
  454. _super = poplib.POP3
  455. class Timed_POP3_SSL(TimerMixin, poplib.POP3_SSL):
  456. _super = poplib.POP3_SSL
  457. class Timed_IMAP4(TimerMixin, imaplib.IMAP4):
  458. _super = imaplib.IMAP4
  459. class Timed_IMAP4_SSL(TimerMixin, imaplib.IMAP4_SSL):
  460. _super = imaplib.IMAP4_SSL