選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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