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.
 
 
 
 
 
 

133 lines
5.0 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. class BulkLimitCrossedError(webnotes.ValidationError): pass
  25. def send(recipients=[], doctype='Profile', email_field='email', first_name_field="first_name",
  26. last_name_field="last_name", subject='[No Subject]', message='[No Content]'):
  27. """send bulk mail if not unsubscribed and within conf.bulk_mail_limit"""
  28. import webnotes
  29. def is_unsubscribed(rdata):
  30. if not rdata: return 1
  31. return rdata[0]['unsubscribed']
  32. def check_bulk_limit(new_mails):
  33. import conf, startup
  34. from webnotes.utils import nowdate
  35. this_month = webnotes.conn.sql("""select count(*) from `tabBulk Email` where
  36. month(creation)=month(%s)""" % nowdate())[0][0]
  37. if hasattr(startup, 'get_monthly_bulk_mail_limit'):
  38. monthly_bulk_mail_limit = startup.get_monthly_bulk_mail_limit()
  39. else:
  40. monthly_bulk_mail_limit = getattr(conf, 'monthly_bulk_mail_limit', 500)
  41. if this_month + len(recipients) > monthly_bulk_mail_limit:
  42. webnotes.msgprint("""Monthly Bulk Mail Limit (%s) Crossed""" % monthly_bulk_mail_limit,
  43. raise_exception=BulkLimitCrossedError)
  44. def add_unsubscribe_link(email):
  45. from webnotes.utils import get_request_site_address
  46. return message + """<div style="padding: 7px; border-top: 1px solid #aaa;
  47. margin-top: 17px;">
  48. <small><a href="%s/server.py?%s">
  49. Unsubscribe</a> from this list.</small></div>""" % (get_request_site_address(),
  50. urllib.urlencode({
  51. "cmd": "webnotes.utils.email_lib.bulk.unsubscribe",
  52. "email": email,
  53. "type": doctype,
  54. "email_field": email_field
  55. }))
  56. def full_name(rdata):
  57. fname = rdata[0].get(first_name_field, '')
  58. lname = rdata[0].get(last_name_field, '')
  59. if fname and not lname:
  60. return fname
  61. elif lname and not fname:
  62. return lname
  63. elif fname and lname:
  64. return fname + ' ' + lname
  65. else:
  66. return rdata[0][email_field].split('@')[0].title()
  67. check_bulk_limit(len(recipients))
  68. sender = webnotes.conn.get_value('Email Settings', None, 'auto_mail_id')
  69. for r in recipients:
  70. rdata = webnotes.conn.sql("""select * from `tab%s` where %s=%s""" % (doctype,
  71. email_field, '%s'), r, as_dict=1)
  72. if not is_unsubscribed(rdata):
  73. # add to queue
  74. add(r, sender, subject, add_unsubscribe_link(r))
  75. def add(email, sender, subject, message):
  76. """add to bulk mail queue"""
  77. from webnotes.model.doc import Document
  78. from webnotes.utils.email_lib.smtp import get_email
  79. e = Document('Bulk Email')
  80. e.sender = sender
  81. e.recipient = email
  82. e.message = get_email(email, sender=e.sender, msg=message, subject=subject).as_string()
  83. e.status = 'Not Sent'
  84. e.save()
  85. @webnotes.whitelist(allow_guest=True)
  86. def unsubscribe():
  87. doctype = webnotes.form_dict.get('type')
  88. field = webnotes.form_dict.get('email_field')
  89. email = webnotes.form_dict.get('email')
  90. webnotes.conn.sql("""update `tab%s` set unsubscribed=1
  91. where `%s`=%s""" % (doctype, field, '%s'), email)
  92. webnotes.unsubscribed_email = email
  93. webnotes.response['type'] = 'page'
  94. webnotes.response['page_name'] = 'unsubscribed.html'
  95. def flush():
  96. """flush email queue, every time: called from scheduler"""
  97. import webnotes
  98. from webnotes.utils.email_lib.smtp import SMTPServer, get_email
  99. smptserver = SMTPServer()
  100. for email in webnotes.conn.sql("""select * from `tabBulk Email` where status='Not Sent'""",
  101. as_dict=1):
  102. webnotes.conn.sql("""update `tabBulk Email` set status='Sending' where name=%s""",
  103. email["name"], auto_commit=True)
  104. try:
  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=True)
  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=True)
  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""")