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.
 
 
 
 
 
 

148 line
4.9 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import webnotes
  5. import HTMLParser
  6. import urllib
  7. from webnotes import msgprint, throw, _
  8. from webnotes.utils.email_lib.smtp import SMTPServer, send
  9. from webnotes.utils.email_lib.email_body import get_email, get_formatted_html
  10. from webnotes.utils.email_lib.html2text import html2text
  11. from webnotes.utils import cint, get_url, nowdate
  12. class BulkLimitCrossedError(webnotes.ValidationError): pass
  13. def send(recipients=None, sender=None, doctype='Profile', email_field='email',
  14. subject='[No Subject]', message='[No Content]', ref_doctype=None, ref_docname=None,
  15. add_unsubscribe_link=True):
  16. def is_unsubscribed(rdata):
  17. if not rdata:
  18. return 1
  19. return cint(rdata.unsubscribed)
  20. def check_bulk_limit(new_mails):
  21. this_month = webnotes.conn.sql("""select count(*) from `tabBulk Email` where
  22. month(creation)=month(%s)""" % nowdate())[0][0]
  23. monthly_bulk_mail_limit = webnotes.conf.get('monthly_bulk_mail_limit') or 500
  24. if this_month + len(recipients) > monthly_bulk_mail_limit:
  25. throw("{bulk} ({limit}) {cross}".format(**{
  26. "bulk": _("Monthly Bulk Mail Limit"),
  27. "limit": monthly_bulk_mail_limit,
  28. "cross": _("crossed")
  29. }), exc=BulkLimitCrossedError)
  30. def update_message(formatted, doc, add_unsubscribe_link):
  31. updated = formatted
  32. if add_unsubscribe_link:
  33. unsubscribe_link = """<div style="padding: 7px; border-top: 1px solid #aaa;
  34. margin-top: 17px;">
  35. <small><a href="%s/?%s">
  36. Unsubscribe</a> from this list.</small></div>""" % (get_url(),
  37. urllib.urlencode({
  38. "cmd": "webnotes.utils.email_lib.bulk.unsubscribe",
  39. "email": doc.get(email_field),
  40. "type": doctype,
  41. "email_field": email_field
  42. }))
  43. updated = updated.replace("<!--unsubscribe link here-->", unsubscribe_link)
  44. return updated
  45. if not recipients: recipients = []
  46. if not sender or sender == "Administrator":
  47. sender = webnotes.conn.get_value('Email Settings', None, 'auto_email_id')
  48. check_bulk_limit(len(recipients))
  49. try:
  50. text_content = html2text(message)
  51. except HTMLParser.HTMLParseError:
  52. text_content = "[See html attachment]"
  53. formatted = get_formatted_html(subject, message)
  54. for r in filter(None, list(set(recipients))):
  55. rdata = webnotes.conn.sql("""select * from `tab%s` where %s=%s""" % (doctype,
  56. email_field, '%s'), (r,), as_dict=1)
  57. doc = rdata and rdata[0] or {}
  58. if not is_unsubscribed(doc):
  59. # add to queue
  60. add(r, sender, subject, update_message(formatted, doc, add_unsubscribe_link),
  61. text_content, ref_doctype, ref_docname)
  62. def add(email, sender, subject, formatted, text_content=None,
  63. ref_doctype=None, ref_docname=None):
  64. """add to bulk mail queue"""
  65. e = webnotes.doc('Bulk Email')
  66. e.sender = sender
  67. e.recipient = email
  68. try:
  69. e.message = get_email(email, sender=e.sender, formatted=formatted, subject=subject,
  70. text_content = text_content).as_string()
  71. except webnotes.ValidationError:
  72. # bad email id - don't add to queue
  73. return
  74. e.status = 'Not Sent'
  75. e.ref_doctype = ref_doctype
  76. e.ref_docname = ref_docname
  77. e.save()
  78. @webnotes.whitelist(allow_guest=True)
  79. def unsubscribe():
  80. doctype = webnotes.form_dict.get('type')
  81. field = webnotes.form_dict.get('email_field')
  82. email = webnotes.form_dict.get('email')
  83. webnotes.conn.sql("""update `tab%s` set unsubscribed=1
  84. where `%s`=%s""" % (doctype, field, '%s'), (email,))
  85. if not webnotes.form_dict.get("from_test"):
  86. webnotes.conn.commit()
  87. webnotes.local.message_title = "Unsubscribe"
  88. webnotes.local.message = "<h3>Unsubscribed</h3><p>%s has been successfully unsubscribed.</p>" % email
  89. webnotes.response['type'] = 'page'
  90. webnotes.response['page_name'] = 'message.html'
  91. def flush(from_test=False):
  92. """flush email queue, every time: called from scheduler"""
  93. smptserver = SMTPServer()
  94. auto_commit = not from_test
  95. if webnotes.flags.mute_emails or webnotes.conf.get("mute_emails") or False:
  96. msgprint(_("Emails are muted"))
  97. from_test = True
  98. for i in xrange(500):
  99. email = webnotes.conn.sql("""select * from `tabBulk Email` where
  100. status='Not Sent' limit 1 for update""", as_dict=1)
  101. if email:
  102. email = email[0]
  103. else:
  104. break
  105. webnotes.conn.sql("""update `tabBulk Email` set status='Sending' where name=%s""",
  106. (email["name"],), auto_commit=auto_commit)
  107. try:
  108. if not from_test:
  109. smptserver.sess.sendmail(email["sender"], email["recipient"], email["message"])
  110. webnotes.conn.sql("""update `tabBulk Email` set status='Sent' where name=%s""",
  111. (email["name"],), auto_commit=auto_commit)
  112. except Exception, e:
  113. webnotes.conn.sql("""update `tabBulk Email` set status='Error', error=%s
  114. where name=%s""", (unicode(e), email["name"]), auto_commit=auto_commit)
  115. def clear_outbox():
  116. """remove mails older than 30 days in Outbox"""
  117. webnotes.conn.sql("""delete from `tabBulk Email` where
  118. datediff(now(), creation) > 30""")