您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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