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.
 
 
 
 
 
 

153 rivejä
5.5 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=None, sender=None, 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. import urllib
  47. return message + """<div style="padding: 7px; border-top: 1px solid #aaa;
  48. margin-top: 17px;">
  49. <small><a href="%s/server.py?%s">
  50. Unsubscribe</a> from this list.</small></div>""" % (get_request_site_address(),
  51. urllib.urlencode({
  52. "cmd": "webnotes.utils.email_lib.bulk.unsubscribe",
  53. "email": email,
  54. "type": doctype,
  55. "email_field": email_field
  56. }))
  57. def full_name(rdata):
  58. fname = rdata[0].get(first_name_field, '')
  59. lname = rdata[0].get(last_name_field, '')
  60. if fname and not lname:
  61. return fname
  62. elif lname and not fname:
  63. return lname
  64. elif fname and lname:
  65. return fname + ' ' + lname
  66. else:
  67. return rdata[0][email_field].split('@')[0].title()
  68. if not recipients: recipients = []
  69. if not sender or sender == "Administrator":
  70. sender = webnotes.conn.get_value('Email Settings', None, 'auto_mail_id')
  71. check_bulk_limit(len(recipients))
  72. import HTMLParser
  73. from webnotes.utils.email_lib.html2text import html2text
  74. try:
  75. text_content = html2text(message)
  76. except HTMLParser.HTMLParseError:
  77. text_content = "[See html attachment]"
  78. for r in recipients:
  79. rdata = webnotes.conn.sql("""select * from `tab%s` where %s=%s""" % (doctype,
  80. email_field, '%s'), r, as_dict=1)
  81. if not is_unsubscribed(rdata):
  82. # add to queue
  83. add(r, sender, subject, add_unsubscribe_link(r), text_content)
  84. def add(email, sender, subject, message, text_content = None):
  85. """add to bulk mail queue"""
  86. from webnotes.model.doc import Document
  87. from webnotes.utils.email_lib.smtp import get_email
  88. e = Document('Bulk Email')
  89. e.sender = sender
  90. e.recipient = email
  91. e.message = get_email(email, sender=e.sender, msg=message, subject=subject,
  92. text_content = text_content).as_string()
  93. e.status = 'Not Sent'
  94. e.save()
  95. @webnotes.whitelist(allow_guest=True)
  96. def unsubscribe():
  97. doctype = webnotes.form_dict.get('type')
  98. field = webnotes.form_dict.get('email_field')
  99. email = webnotes.form_dict.get('email')
  100. webnotes.conn.sql("""update `tab%s` set unsubscribed=1
  101. where `%s`=%s""" % (doctype, field, '%s'), email)
  102. webnotes.unsubscribed_email = email
  103. webnotes.response['type'] = 'page'
  104. webnotes.response['page_name'] = 'unsubscribed.html'
  105. def flush():
  106. """flush email queue, every time: called from scheduler"""
  107. import webnotes
  108. from webnotes.utils.email_lib.smtp import SMTPServer, get_email
  109. smptserver = SMTPServer()
  110. for i in xrange(500):
  111. email = webnotes.conn.sql("""select * from `tabBulk Email` where
  112. status='Not Sent' limit 1 for update""", as_dict=1)
  113. if email:
  114. email = email[0]
  115. else:
  116. break
  117. webnotes.conn.sql("""update `tabBulk Email` set status='Sending' where name=%s""",
  118. email["name"], auto_commit=True)
  119. try:
  120. smptserver.sess.sendmail(email["sender"], email["recipient"], email["message"])
  121. webnotes.conn.sql("""update `tabBulk Email` set status='Sent' where name=%s""",
  122. email["name"], auto_commit=True)
  123. except Exception, e:
  124. webnotes.conn.sql("""update `tabBulk Email` set status='Error', error=%s
  125. where name=%s""", (unicode(e), email["name"]), auto_commit=True)
  126. def clear_outbox():
  127. """remove mails older than 30 days in Outbox"""
  128. webnotes.conn.sql("""delete from `tabBulk Email` where
  129. datediff(now(), creation) > 30""")