Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

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