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

534 行
18 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. from six.moves import range
  5. import frappe
  6. import HTMLParser
  7. import smtplib, quopri, json
  8. from frappe import msgprint, throw, _
  9. from frappe.email.smtp import SMTPServer, get_outgoing_email_account
  10. from frappe.email.email_body import get_email, get_formatted_html, add_attachment
  11. from frappe.utils.verified_command import get_signed_params, verify_request
  12. from html2text import html2text
  13. from frappe.utils import get_url, nowdate, encode, now_datetime, add_days, split_emails, cstr, cint
  14. from frappe.utils.file_manager import get_file
  15. from rq.timeouts import JobTimeoutException
  16. from frappe.utils.scheduler import log
  17. class EmailLimitCrossedError(frappe.ValidationError): pass
  18. def send(recipients=None, sender=None, subject=None, message=None, text_content=None, reference_doctype=None,
  19. reference_name=None, unsubscribe_method=None, unsubscribe_params=None, unsubscribe_message=None,
  20. attachments=None, reply_to=None, cc=[], message_id=None, in_reply_to=None, send_after=None,
  21. expose_recipients=None, send_priority=1, communication=None, now=False, read_receipt=None,
  22. queue_separately=False, is_notification=False, add_unsubscribe_link=1, inline_images=None,
  23. header=None):
  24. """Add email to sending queue (Email Queue)
  25. :param recipients: List of recipients.
  26. :param sender: Email sender.
  27. :param subject: Email subject.
  28. :param message: Email message.
  29. :param text_content: Text version of email message.
  30. :param reference_doctype: Reference DocType of caller document.
  31. :param reference_name: Reference name of caller document.
  32. :param send_priority: Priority for Email Queue, default 1.
  33. :param unsubscribe_method: URL method for unsubscribe. Default is `/api/method/frappe.email.queue.unsubscribe`.
  34. :param unsubscribe_params: additional params for unsubscribed links. default are name, doctype, email
  35. :param attachments: Attachments to be sent.
  36. :param reply_to: Reply to be captured here (default inbox)
  37. :param in_reply_to: Used to send the Message-Id of a received email back as In-Reply-To.
  38. :param send_after: Send this email after the given datetime. If value is in integer, then `send_after` will be the automatically set to no of days from current date.
  39. :param communication: Communication link to be set in Email Queue record
  40. :param now: Send immediately (don't send in the background)
  41. :param queue_separately: Queue each email separately
  42. :param is_notification: Marks email as notification so will not trigger notifications from system
  43. :param add_unsubscribe_link: Send unsubscribe link in the footer of the Email, default 1.
  44. :param inline_images: List of inline images as {"filename", "filecontent"}. All src properties will be replaced with random Content-Id
  45. :param header: Append header in email (boolean)
  46. """
  47. if not unsubscribe_method:
  48. unsubscribe_method = "/api/method/frappe.email.queue.unsubscribe"
  49. if not recipients and not cc:
  50. return
  51. if isinstance(recipients, basestring):
  52. recipients = split_emails(recipients)
  53. if isinstance(cc, basestring):
  54. cc = split_emails(cc)
  55. if isinstance(send_after, int):
  56. send_after = add_days(nowdate(), send_after)
  57. email_account = get_outgoing_email_account(True, append_to=reference_doctype)
  58. if not sender or sender == "Administrator":
  59. sender = email_account.default_sender
  60. check_email_limit(recipients)
  61. if not text_content:
  62. try:
  63. text_content = html2text(message)
  64. except HTMLParser.HTMLParseError:
  65. text_content = "See html attachment"
  66. if reference_doctype and reference_name:
  67. unsubscribed = [d.email for d in frappe.db.get_all("Email Unsubscribe", "email",
  68. {"reference_doctype": reference_doctype, "reference_name": reference_name})]
  69. unsubscribed += [d.email for d in frappe.db.get_all("Email Unsubscribe", "email",
  70. {"global_unsubscribe": 1})]
  71. else:
  72. unsubscribed = []
  73. recipients = [r for r in list(set(recipients)) if r and r not in unsubscribed]
  74. email_text_context = text_content
  75. should_append_unsubscribe = (add_unsubscribe_link
  76. and reference_doctype
  77. and (unsubscribe_message or reference_doctype=="Newsletter")
  78. and add_unsubscribe_link==1)
  79. unsubscribe_link = None
  80. if should_append_unsubscribe or True:
  81. unsubscribe_link = get_unsubscribe_message(unsubscribe_message, expose_recipients)
  82. email_text_context += unsubscribe_link.text
  83. email_content = get_formatted_html(subject, message,
  84. email_account=email_account, header=header,
  85. unsubscribe_link=unsubscribe_link)
  86. # add to queue
  87. add(recipients, sender, subject,
  88. formatted=email_content,
  89. text_content=email_text_context,
  90. reference_doctype=reference_doctype,
  91. reference_name=reference_name,
  92. attachments=attachments,
  93. reply_to=reply_to,
  94. cc=cc,
  95. message_id=message_id,
  96. in_reply_to=in_reply_to,
  97. send_after=send_after,
  98. send_priority=send_priority,
  99. email_account=email_account,
  100. communication=communication,
  101. add_unsubscribe_link=add_unsubscribe_link,
  102. unsubscribe_method=unsubscribe_method,
  103. unsubscribe_params=unsubscribe_params,
  104. expose_recipients=expose_recipients,
  105. read_receipt=read_receipt,
  106. queue_separately=queue_separately,
  107. is_notification = is_notification,
  108. inline_images = inline_images,
  109. header=header,
  110. now=now)
  111. def add(recipients, sender, subject, **kwargs):
  112. """Add to Email Queue"""
  113. if kwargs.get('queue_separately') or len(recipients) > 20:
  114. email_queue = None
  115. for r in recipients:
  116. if not email_queue:
  117. email_queue = get_email_queue([r], sender, subject, **kwargs)
  118. if kwargs.get('now'):
  119. email_queue(email_queue.name, now=True)
  120. else:
  121. duplicate = email_queue.get_duplicate([r])
  122. duplicate.insert(ignore_permissions=True)
  123. if kwargs.get('now'):
  124. send_one(duplicate.name, now=True)
  125. frappe.db.commit()
  126. else:
  127. email_queue = get_email_queue(recipients, sender, subject, **kwargs)
  128. if kwargs.get('now'):
  129. send_one(email_queue.name, now=True)
  130. def get_email_queue(recipients, sender, subject, **kwargs):
  131. '''Make Email Queue object'''
  132. e = frappe.new_doc('Email Queue')
  133. e.priority = kwargs.get('send_priority')
  134. attachments = kwargs.get('attachments')
  135. if attachments:
  136. # store attachments with fid, to be attached on-demand later
  137. _attachments = []
  138. for att in attachments:
  139. if att.get('fid'):
  140. _attachments.append(att)
  141. e.attachments = json.dumps(_attachments)
  142. try:
  143. mail = get_email(recipients,
  144. sender=sender,
  145. subject=subject,
  146. formatted=kwargs.get('formatted'),
  147. text_content=kwargs.get('text_content'),
  148. attachments=kwargs.get('attachments'),
  149. reply_to=kwargs.get('reply_to'),
  150. cc=kwargs.get('cc'),
  151. email_account=kwargs.get('email_account'),
  152. expose_recipients=kwargs.get('expose_recipients'),
  153. inline_images=kwargs.get('inline_images'),
  154. header=kwargs.get('header'))
  155. mail.set_message_id(kwargs.get('message_id'),kwargs.get('is_notification'))
  156. if kwargs.get('read_receipt'):
  157. mail.msg_root["Disposition-Notification-To"] = sender
  158. if kwargs.get('in_reply_to'):
  159. mail.set_in_reply_to(kwargs.get('in_reply_to'))
  160. e.message_id = mail.msg_root["Message-Id"].strip(" <>")
  161. e.message = cstr(mail.as_string())
  162. e.sender = mail.sender
  163. except frappe.InvalidEmailAddressError:
  164. # bad Email Address - don't add to queue
  165. frappe.log_error('Invalid Email ID Sender: {0}, Recipients: {1}'.format(mail.sender,
  166. ', '.join(mail.recipients)), 'Email Not Sent')
  167. e.set_recipients(recipients + kwargs.get('cc', []))
  168. e.reference_doctype = kwargs.get('reference_doctype')
  169. e.reference_name = kwargs.get('reference_name')
  170. e.add_unsubscribe_link = kwargs.get("add_unsubscribe_link")
  171. e.unsubscribe_method = kwargs.get('unsubscribe_method')
  172. e.unsubscribe_params = kwargs.get('unsubscribe_params')
  173. e.expose_recipients = kwargs.get('expose_recipients')
  174. e.communication = kwargs.get('communication')
  175. e.send_after = kwargs.get('send_after')
  176. e.show_as_cc = ",".join(kwargs.get('cc', []))
  177. e.insert(ignore_permissions=True)
  178. return e
  179. def check_email_limit(recipients):
  180. # if using settings from site_config.json, check email limit
  181. # No limit for own email settings
  182. smtp_server = SMTPServer()
  183. if (smtp_server.email_account
  184. and getattr(smtp_server.email_account, "from_site_config", False)
  185. or frappe.flags.in_test):
  186. monthly_email_limit = frappe.conf.get('limits', {}).get('emails')
  187. if frappe.flags.in_test:
  188. monthly_email_limit = 500
  189. if not monthly_email_limit:
  190. return
  191. # get count of mails sent this month
  192. this_month = get_emails_sent_this_month()
  193. if (this_month + len(recipients)) > monthly_email_limit:
  194. throw(_("Cannot send this email. You have crossed the sending limit of {0} emails for this month.").format(monthly_email_limit),
  195. EmailLimitCrossedError)
  196. def get_emails_sent_this_month():
  197. return frappe.db.sql("""select count(name) from `tabEmail Queue` where
  198. status='Sent' and MONTH(creation)=MONTH(CURDATE())""")[0][0]
  199. def get_unsubscribe_message(unsubscribe_message, expose_recipients):
  200. if unsubscribe_message:
  201. unsubscribe_html = '''<a href="<!--unsubscribe url-->"
  202. target="_blank">{0}</a>'''.format(unsubscribe_message)
  203. else:
  204. unsubscribe_link = '''<a href="<!--unsubscribe url-->"
  205. target="_blank">{0}</a>'''.format(_('Unsubscribe'))
  206. unsubscribe_html = _("{0} to stop receiving emails of this type").format(unsubscribe_link)
  207. html = """<div class="email-unsubscribe">
  208. <!--cc message-->
  209. <div>
  210. {0}
  211. </div>
  212. </div>""".format(unsubscribe_html)
  213. if expose_recipients == "footer":
  214. text = "\n<!--cc message-->"
  215. else:
  216. text = ""
  217. text += "\n\n{unsubscribe_message}: <!--unsubscribe url-->\n".format(unsubscribe_message=unsubscribe_message)
  218. return frappe._dict({
  219. "html": html,
  220. "text": text
  221. })
  222. def get_unsubcribed_url(reference_doctype, reference_name, email, unsubscribe_method, unsubscribe_params):
  223. params = {"email": email.encode("utf-8"),
  224. "doctype": reference_doctype.encode("utf-8"),
  225. "name": reference_name.encode("utf-8")}
  226. if unsubscribe_params:
  227. params.update(unsubscribe_params)
  228. query_string = get_signed_params(params)
  229. # for test
  230. frappe.local.flags.signed_query_string = query_string
  231. return get_url(unsubscribe_method + "?" + get_signed_params(params))
  232. @frappe.whitelist(allow_guest=True)
  233. def unsubscribe(doctype, name, email):
  234. # unsubsribe from comments and communications
  235. if not verify_request():
  236. return
  237. try:
  238. frappe.get_doc({
  239. "doctype": "Email Unsubscribe",
  240. "email": email,
  241. "reference_doctype": doctype,
  242. "reference_name": name
  243. }).insert(ignore_permissions=True)
  244. except frappe.DuplicateEntryError:
  245. frappe.db.rollback()
  246. else:
  247. frappe.db.commit()
  248. return_unsubscribed_page(email, doctype, name)
  249. def return_unsubscribed_page(email, doctype, name):
  250. frappe.respond_as_web_page(_("Unsubscribed"),
  251. _("{0} has left the conversation in {1} {2}").format(email, _(doctype), name),
  252. indicator_color='green')
  253. def flush(from_test=False):
  254. """flush email queue, every time: called from scheduler"""
  255. # additional check
  256. cache = frappe.cache()
  257. check_email_limit([])
  258. auto_commit = not from_test
  259. if frappe.are_emails_muted():
  260. msgprint(_("Emails are muted"))
  261. from_test = True
  262. smtpserver = SMTPServer()
  263. make_cache_queue()
  264. for i in range(cache.llen('cache_email_queue')):
  265. email = cache.lpop('cache_email_queue')
  266. if cint(frappe.defaults.get_defaults().get("hold_queue"))==1:
  267. break
  268. if email:
  269. send_one(email, smtpserver, auto_commit, from_test=from_test)
  270. # NOTE: removing commit here because we pass auto_commit
  271. # finally:
  272. # frappe.db.commit()
  273. def make_cache_queue():
  274. '''cache values in queue before sendign'''
  275. cache = frappe.cache()
  276. emails = frappe.db.sql('''select
  277. name
  278. from
  279. `tabEmail Queue`
  280. where
  281. (status='Not Sent' or status='Partially Sent') and
  282. (send_after is null or send_after < %(now)s)
  283. order
  284. by priority desc, creation asc
  285. limit 500''', { 'now': now_datetime() })
  286. # reset value
  287. cache.delete_value('cache_email_queue')
  288. for e in emails:
  289. cache.rpush('cache_email_queue', e[0])
  290. def send_one(email, smtpserver=None, auto_commit=True, now=False, from_test=False):
  291. '''Send Email Queue with given smtpserver'''
  292. email = frappe.db.sql('''select
  293. name, status, communication, message, sender, reference_doctype,
  294. reference_name, unsubscribe_param, unsubscribe_method, expose_recipients,
  295. show_as_cc, add_unsubscribe_link, attachments
  296. from
  297. `tabEmail Queue`
  298. where
  299. name=%s
  300. for update''', email, as_dict=True)[0]
  301. recipients_list = frappe.db.sql('''select name, recipient, status from
  302. `tabEmail Queue Recipient` where parent=%s''',email.name,as_dict=1)
  303. if frappe.are_emails_muted():
  304. frappe.msgprint(_("Emails are muted"))
  305. return
  306. if cint(frappe.defaults.get_defaults().get("hold_queue"))==1 :
  307. return
  308. if email.status not in ('Not Sent','Partially Sent') :
  309. # rollback to release lock and return
  310. frappe.db.rollback()
  311. return
  312. frappe.db.sql("""update `tabEmail Queue` set status='Sending', modified=%s where name=%s""",
  313. (now_datetime(), email.name), auto_commit=auto_commit)
  314. if email.communication:
  315. frappe.get_doc('Communication', email.communication).set_delivery_status(commit=auto_commit)
  316. try:
  317. if not frappe.flags.in_test:
  318. if not smtpserver: smtpserver = SMTPServer()
  319. smtpserver.setup_email_account(email.reference_doctype)
  320. for recipient in recipients_list:
  321. if recipient.status != "Not Sent":
  322. continue
  323. message = prepare_message(email, recipient.recipient, recipients_list)
  324. if not frappe.flags.in_test:
  325. smtpserver.sess.sendmail(email.sender, recipient.recipient, encode(message))
  326. recipient.status = "Sent"
  327. frappe.db.sql("""update `tabEmail Queue Recipient` set status='Sent', modified=%s where name=%s""",
  328. (now_datetime(), recipient.name), auto_commit=auto_commit)
  329. #if all are sent set status
  330. if any("Sent" == s.status for s in recipients_list):
  331. frappe.db.sql("""update `tabEmail Queue` set status='Sent', modified=%s where name=%s""",
  332. (now_datetime(), email.name), auto_commit=auto_commit)
  333. else:
  334. frappe.db.sql("""update `tabEmail Queue` set status='Error', error=%s
  335. where name=%s""", ("No recipients to send to", email.name), auto_commit=auto_commit)
  336. if frappe.flags.in_test:
  337. frappe.flags.sent_mail = message
  338. return
  339. if email.communication:
  340. frappe.get_doc('Communication', email.communication).set_delivery_status(commit=auto_commit)
  341. except (smtplib.SMTPServerDisconnected,
  342. smtplib.SMTPConnectError,
  343. smtplib.SMTPHeloError,
  344. smtplib.SMTPAuthenticationError,
  345. JobTimeoutException):
  346. # bad connection/timeout, retry later
  347. if any("Sent" == s.status for s in recipients_list):
  348. frappe.db.sql("""update `tabEmail Queue` set status='Partially Sent', modified=%s where name=%s""",
  349. (now_datetime(), email.name), auto_commit=auto_commit)
  350. else:
  351. frappe.db.sql("""update `tabEmail Queue` set status='Not Sent', modified=%s where name=%s""",
  352. (now_datetime(), email.name), auto_commit=auto_commit)
  353. if email.communication:
  354. frappe.get_doc('Communication', email.communication).set_delivery_status(commit=auto_commit)
  355. # no need to attempt further
  356. return
  357. except Exception as e:
  358. frappe.db.rollback()
  359. if any("Sent" == s.status for s in recipients_list):
  360. frappe.db.sql("""update `tabEmail Queue` set status='Partially Errored', error=%s where name=%s""",
  361. (unicode(e), email.name), auto_commit=auto_commit)
  362. else:
  363. frappe.db.sql("""update `tabEmail Queue` set status='Error', error=%s
  364. where name=%s""", (unicode(e), email.name), auto_commit=auto_commit)
  365. if email.communication:
  366. frappe.get_doc('Communication', email.communication).set_delivery_status(commit=auto_commit)
  367. if now:
  368. print(frappe.get_traceback())
  369. raise e
  370. else:
  371. # log to Error Log
  372. log('frappe.email.queue.flush', unicode(e))
  373. def prepare_message(email, recipient, recipients_list):
  374. message = email.message
  375. if not message:
  376. return ""
  377. if email.add_unsubscribe_link and email.reference_doctype: # is missing the check for unsubscribe message but will not add as there will be no unsubscribe url
  378. unsubscribe_url = get_unsubcribed_url(email.reference_doctype, email.reference_name, recipient,
  379. email.unsubscribe_method, email.unsubscribe_params)
  380. message = message.replace("<!--unsubscribe url-->", quopri.encodestring(unsubscribe_url))
  381. if email.expose_recipients == "header":
  382. pass
  383. else:
  384. if email.expose_recipients == "footer":
  385. if isinstance(email.show_as_cc, basestring):
  386. email.show_as_cc = email.show_as_cc.split(",")
  387. email_sent_to = [r.recipient for r in recipients_list]
  388. email_sent_cc = ", ".join([e for e in email_sent_to if e in email.show_as_cc])
  389. email_sent_to = ", ".join([e for e in email_sent_to if e not in email.show_as_cc])
  390. if email_sent_cc:
  391. email_sent_message = _("This email was sent to {0} and copied to {1}").format(email_sent_to,email_sent_cc)
  392. else:
  393. email_sent_message = _("This email was sent to {0}").format(email_sent_to)
  394. message = message.replace("<!--cc message-->", quopri.encodestring(email_sent_message))
  395. message = message.replace("<!--recipient-->", recipient)
  396. message = (message and message.encode('utf8')) or ''
  397. if not email.attachments:
  398. return message
  399. # On-demand attachments
  400. from email.parser import Parser
  401. msg_obj = Parser().parsestr(message)
  402. attachments = json.loads(email.attachments)
  403. for attachment in attachments:
  404. if attachment.get('fcontent'): continue
  405. fid = attachment.get('fid')
  406. if not fid: continue
  407. fname, fcontent = get_file(fid)
  408. attachment.update({
  409. 'fname': fname,
  410. 'fcontent': fcontent,
  411. 'parent': msg_obj
  412. })
  413. attachment.pop("fid", None)
  414. add_attachment(**attachment)
  415. return msg_obj.as_string()
  416. def clear_outbox():
  417. """Remove low priority older than 31 days in Outbox and expire mails not sent for 7 days.
  418. Called daily via scheduler.
  419. Note: Used separate query to avoid deadlock
  420. """
  421. email_queues = frappe.db.sql_list("""select name from `tabEmail Queue`
  422. where priority=0 and datediff(now(), modified) > 31""")
  423. if email_queues:
  424. frappe.db.sql("""delete from `tabEmail Queue` where name in (%s)"""
  425. % ','.join(['%s']*len(email_queues)), tuple(email_queues))
  426. frappe.db.sql("""delete from `tabEmail Queue Recipient` where parent in (%s)"""
  427. % ','.join(['%s']*len(email_queues)), tuple(email_queues))
  428. frappe.db.sql("""
  429. update `tabEmail Queue`
  430. set status='Expired'
  431. where datediff(curdate(), modified) > 7 and status='Not Sent' and (send_after is null or send_after < %(now)s)""", { 'now': now_datetime() })