Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

152 řádky
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. from webnotes.model.doc import Document
  6. from webnotes.utils import cint, get_url
  7. import urllib
  8. class BulkLimitCrossedError(webnotes.ValidationError): pass
  9. def send(recipients=None, sender=None, doctype='Profile', email_field='email',
  10. subject='[No Subject]', message='[No Content]', ref_doctype=None, ref_docname=None,
  11. add_unsubscribe_link=True):
  12. """send bulk mail if not unsubscribed and within conf.bulk_mail_limit"""
  13. import webnotes
  14. def is_unsubscribed(rdata):
  15. if not rdata: return 1
  16. return cint(rdata.unsubscribed)
  17. def check_bulk_limit(new_mails):
  18. from webnotes import conf
  19. from webnotes.utils import nowdate
  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 = 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(doc):
  27. updated = message
  28. if add_unsubscribe_link:
  29. updated += """<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. return updated
  40. if not recipients: recipients = []
  41. if not sender or sender == "Administrator":
  42. sender = webnotes.conn.get_value('Email Settings', None, 'auto_email_id')
  43. check_bulk_limit(len(recipients))
  44. import HTMLParser
  45. from webnotes.utils.email_lib.html2text import html2text
  46. from webnotes.utils import expand_partial_links
  47. try:
  48. message = expand_partial_links(message)
  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:
  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.local.message_title = "Unsubscribe"
  85. webnotes.local.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
  91. from webnotes import conf
  92. from webnotes.utils.email_lib.smtp import SMTPServer, get_email
  93. smptserver = SMTPServer()
  94. auto_commit = not from_test
  95. if webnotes.flags.mute_emails or conf.get("mute_emails") or False:
  96. webnotes.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""")