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.
 
 
 
 
 
 

150 lines
4.8 KiB

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