Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

142 rader
5.1 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. from __future__ import unicode_literals
  23. import webnotes
  24. from webnotes.model.doc import Document
  25. class BulkLimitCrossedError(webnotes.ValidationError): pass
  26. def send(recipients=None, sender=None, doctype='Profile', email_field='email',
  27. subject='[No Subject]', message='[No Content]'):
  28. """send bulk mail if not unsubscribed and within conf.bulk_mail_limit"""
  29. import webnotes
  30. def is_unsubscribed(rdata):
  31. if not rdata: return 1
  32. return rdata[0]['unsubscribed']
  33. def check_bulk_limit(new_mails):
  34. import conf, startup
  35. from webnotes.utils import nowdate
  36. this_month = webnotes.conn.sql("""select count(*) from `tabBulk Email` where
  37. month(creation)=month(%s)""" % nowdate())[0][0]
  38. if hasattr(startup, 'get_monthly_bulk_mail_limit'):
  39. monthly_bulk_mail_limit = startup.get_monthly_bulk_mail_limit()
  40. else:
  41. monthly_bulk_mail_limit = getattr(conf, 'monthly_bulk_mail_limit', 500)
  42. if this_month + len(recipients) > monthly_bulk_mail_limit:
  43. webnotes.msgprint("""Monthly Bulk Mail Limit (%s) Crossed""" % monthly_bulk_mail_limit,
  44. raise_exception=BulkLimitCrossedError)
  45. def add_unsubscribe_link(email):
  46. from webnotes.utils import get_request_site_address
  47. import urllib
  48. return message + """<div style="padding: 7px; border-top: 1px solid #aaa;
  49. margin-top: 17px;">
  50. <small><a href="%s/server.py?%s">
  51. Unsubscribe</a> from this list.</small></div>""" % (get_request_site_address(),
  52. urllib.urlencode({
  53. "cmd": "webnotes.utils.email_lib.bulk.unsubscribe",
  54. "email": email,
  55. "type": doctype,
  56. "email_field": email_field
  57. }))
  58. if not recipients: recipients = []
  59. if not sender or sender == "Administrator":
  60. sender = webnotes.conn.get_value('Email Settings', None, 'auto_mail_id')
  61. check_bulk_limit(len(recipients))
  62. import HTMLParser
  63. from webnotes.utils.email_lib.html2text import html2text
  64. try:
  65. text_content = html2text(message)
  66. except HTMLParser.HTMLParseError:
  67. text_content = "[See html attachment]"
  68. for r in list(set(recipients)):
  69. rdata = webnotes.conn.sql("""select * from `tab%s` where %s=%s""" % (doctype,
  70. email_field, '%s'), r, as_dict=1)
  71. if not is_unsubscribed(rdata):
  72. # add to queue
  73. add(r, sender, subject, add_unsubscribe_link(r), text_content)
  74. def add(email, sender, subject, message, text_content = None):
  75. """add to bulk mail queue"""
  76. from webnotes.utils.email_lib.smtp import get_email
  77. e = Document('Bulk Email')
  78. e.sender = sender
  79. e.recipient = email
  80. e.message = get_email(email, sender=e.sender, msg=message, subject=subject,
  81. text_content = text_content).as_string()
  82. e.status = 'Not Sent'
  83. e.save()
  84. @webnotes.whitelist(allow_guest=True)
  85. def unsubscribe():
  86. doctype = webnotes.form_dict.get('type')
  87. field = webnotes.form_dict.get('email_field')
  88. email = webnotes.form_dict.get('email')
  89. webnotes.conn.sql("""update `tab%s` set unsubscribed=1
  90. where `%s`=%s""" % (doctype, field, '%s'), email)
  91. webnotes.unsubscribed_email = email
  92. webnotes.response['type'] = 'page'
  93. webnotes.response['page_name'] = 'unsubscribed.html'
  94. def flush():
  95. """flush email queue, every time: called from scheduler"""
  96. import webnotes
  97. from webnotes.utils.email_lib.smtp import SMTPServer, get_email
  98. smptserver = SMTPServer()
  99. for i in xrange(500):
  100. email = webnotes.conn.sql("""select * from `tabBulk Email` where
  101. status='Not Sent' limit 1 for update""", as_dict=1)
  102. if email:
  103. email = email[0]
  104. else:
  105. break
  106. webnotes.conn.sql("""update `tabBulk Email` set status='Sending' where name=%s""",
  107. email["name"], auto_commit=True)
  108. try:
  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=True)
  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=True)
  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""")