Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

149 linhas
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 conf, startup
  17. from webnotes.utils import nowdate
  18. this_month = webnotes.conn.sql("""select count(*) from `tabBulk Email` where
  19. month(creation)=month(%s)""" % nowdate())[0][0]
  20. if hasattr(startup, 'get_monthly_bulk_mail_limit'):
  21. monthly_bulk_mail_limit = startup.get_monthly_bulk_mail_limit()
  22. else:
  23. monthly_bulk_mail_limit = getattr(conf, 'monthly_bulk_mail_limit', 500)
  24. if this_month + len(recipients) > monthly_bulk_mail_limit:
  25. webnotes.msgprint("""Monthly Bulk Mail Limit (%s) Crossed""" % monthly_bulk_mail_limit,
  26. raise_exception=BulkLimitCrossedError)
  27. def update_message(doc):
  28. from webnotes.utils import get_request_site_address
  29. import urllib
  30. updated = message + """<div style="padding: 7px; border-top: 1px solid #aaa;
  31. margin-top: 17px;">
  32. <small><a href="%s/server.py?%s">
  33. Unsubscribe</a> from this list.</small></div>""" % (get_request_site_address(),
  34. urllib.urlencode({
  35. "cmd": "webnotes.utils.email_lib.bulk.unsubscribe",
  36. "email": doc.get(email_field),
  37. "type": doctype,
  38. "email_field": email_field
  39. }))
  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. import HTMLParser
  46. from webnotes.utils.email_lib.html2text import html2text
  47. try:
  48. text_content = html2text(message)
  49. except HTMLParser.HTMLParseError:
  50. text_content = "[See html attachment]"
  51. for r in filter(None, list(set(recipients))):
  52. rdata = webnotes.conn.sql("""select * from `tab%s` where %s=%s""" % (doctype,
  53. email_field, '%s'), r, as_dict=1)
  54. doc = rdata and rdata[0] or {}
  55. if not is_unsubscribed(doc):
  56. # add to queue
  57. add(r, sender, subject, update_message(doc), text_content, ref_doctype, ref_docname)
  58. def add(email, sender, subject, message, text_content=None, ref_doctype=None, ref_docname=None):
  59. """add to bulk mail queue"""
  60. from webnotes.utils.email_lib.smtp import get_email
  61. e = Document('Bulk Email')
  62. e.sender = sender
  63. e.recipient = email
  64. try:
  65. e.message = get_email(email, sender=e.sender, msg=message, subject=subject,
  66. text_content = text_content).as_string()
  67. except webnotes.ValidationError, e:
  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.message_title = "Unsubscribe"
  84. webnotes.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. import webnotes, conf
  90. from webnotes.utils.email_lib.smtp import SMTPServer, get_email
  91. smptserver = SMTPServer()
  92. auto_commit = not from_test
  93. if webnotes.mute_emails or getattr(conf, "mute_emails", False):
  94. webnotes.msgprint("Emails are muted")
  95. from_test = True
  96. for i in xrange(500):
  97. email = webnotes.conn.sql("""select * from `tabBulk Email` where
  98. status='Not Sent' limit 1 for update""", as_dict=1)
  99. if email:
  100. email = email[0]
  101. else:
  102. break
  103. webnotes.conn.sql("""update `tabBulk Email` set status='Sending' where name=%s""",
  104. email["name"], auto_commit=auto_commit)
  105. try:
  106. if not from_test:
  107. smptserver.sess.sendmail(email["sender"], email["recipient"], email["message"])
  108. webnotes.conn.sql("""update `tabBulk Email` set status='Sent' where name=%s""",
  109. email["name"], auto_commit=auto_commit)
  110. except Exception, e:
  111. webnotes.conn.sql("""update `tabBulk Email` set status='Error', error=%s
  112. where name=%s""", (unicode(e), email["name"]), auto_commit=auto_commit)
  113. def clear_outbox():
  114. """remove mails older than 30 days in Outbox"""
  115. webnotes.conn.sql("""delete from `tabBulk Email` where
  116. datediff(now(), creation) > 30""")