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.
 
 
 
 
 
 

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