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.
 
 
 
 
 
 

209 lines
5.9 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.utils import cint
  25. from webnotes.utils.email_lib.smtp import EMail
  26. class FormEmail:
  27. """
  28. Represents an email sent from a Form
  29. """
  30. def __init__(self):
  31. """
  32. Get paramteres from the cgi form object
  33. """
  34. self.__dict__.update(webnotes.form_dict)
  35. self.recipients = None
  36. if self.sendto:
  37. self.recipients = self.sendto.replace(';', ',')
  38. self.recipients = self.recipients.split(',')
  39. def update_contacts(self):
  40. """
  41. Add new email contact to database
  42. """
  43. import webnotes
  44. from webnotes.model.doc import Document
  45. for r in self.recipients:
  46. r = r.strip()
  47. try:
  48. if not webnotes.conn.sql("select email_id from tabContact where email_id=%s", r):
  49. d = Document('Contact')
  50. d.email_id = r
  51. d.save(1)
  52. except Exception, e:
  53. if e.args[0]==1146: pass # no table
  54. else: raise e
  55. def make_full_links(self):
  56. """
  57. Adds server name the relative links, so that images etc can be seen correctly
  58. """
  59. # only domain
  60. if not self.__dict__.get('full_domain'):
  61. return
  62. def make_full_link(match):
  63. import os
  64. link = match.group('name')
  65. if not link.startswith('http'):
  66. link = os.path.join(self.full_domain, link)
  67. return 'src="%s"' % link
  68. import re
  69. p = re.compile('src[ ]*=[ ]*" (?P<name> [^"]*) "', re.VERBOSE)
  70. self.body = p.sub(make_full_link, self.body)
  71. p = re.compile("src[ ]*=[ ]*' (?P<name> [^']*) '", re.VERBOSE)
  72. self.body = p.sub(make_full_link, self.body)
  73. def get_form_link(self):
  74. """
  75. Returns publicly accessible form link
  76. """
  77. public_domain = webnotes.conn.get_value('Control Panel', None, 'public_domain')
  78. from webnotes.utils.encrypt import encrypt
  79. if not public_domain:
  80. return ''
  81. args = {
  82. 'dt': self.dt,
  83. 'dn':self.dn,
  84. 'acx': webnotes.conn.get_value('Control Panel', None, 'account_id'),
  85. 'server': public_domain,
  86. 'akey': encrypt(self.dn)
  87. }
  88. return '<div>If you are unable to view the form below <a href="http://%(server)s/index.cgi?page=Form/%(dt)s/%(dn)s&acx=%(acx)s&akey=%(akey)s">click here to see it in your browser</div>' % args
  89. def set_attachments(self):
  90. """
  91. Set attachments to the email from the form
  92. """
  93. al = []
  94. try:
  95. al = webnotes.conn.sql('select file_list from `tab%s` where name="%s"' % (webnotes.form_dict.get('dt'), webnotes.form_dict.get('dn')))
  96. if al:
  97. al = (al[0][0] or '').split('\n')
  98. except Exception, e:
  99. if e.args[0]==1146:
  100. pass # no attachments in single types!
  101. else:
  102. raise Exception, e
  103. return al
  104. def build_message(self):
  105. """
  106. Builds the message object
  107. """
  108. self.email = EMail(self.sendfrom, self.recipients, self.subject, alternative = 1)
  109. from webnotes.utils.email_lib.html2text import html2text
  110. self.make_full_links()
  111. # message
  112. if not self.__dict__.get('message'):
  113. self.message = 'Please find attached %s: %s\n' % (self.dt, self.dn)
  114. html_message = text_message = self.message.replace('\n','<br>')
  115. # separator
  116. html_message += '<div style="margin:17px 0px; border-bottom:1px solid #AAA"></div>'
  117. # form itself (only in the html message)
  118. html_message += self.body
  119. # message as text
  120. self.email.set_text(html2text(text_message))
  121. self.email.set_html(html_message)
  122. def make_communication(self):
  123. """make email communication"""
  124. from webnotes.model.doc import Document
  125. from webnotes.utils import nowdate
  126. comm = Document('Communication')
  127. comm.communication_medium = 'Email'
  128. comm.subject = self.subject
  129. comm.content = self.message
  130. comm.category = 'Sent Mail'
  131. comm.action = 'Sent Mail'
  132. comm.naming_series = 'COMM-'
  133. comm.user = webnotes.session["user"]
  134. comm.communication_date = nowdate()
  135. comm.email_address = ", ".join(self.recipients)
  136. try:
  137. comm_cols = [c[0] for c in webnotes.conn.sql("""desc tabCommunication""")]
  138. # tag to record
  139. dt = self.dt.lower().replace(" ", "_")
  140. if dt in comm_cols:
  141. comm.fields[dt] = self.dn
  142. # tag to customer, supplier (?)
  143. if self.customer:
  144. comm.customer = self.customer
  145. if self.supplier:
  146. comm.supplier = self.supplier
  147. comm.save(1)
  148. except Exception, e:
  149. if e.args[0]!=1146: raise e
  150. def send(self):
  151. """
  152. Send the form with html attachment
  153. """
  154. if not self.recipients:
  155. webnotes.msgprint('No one to send to!')
  156. return
  157. self.build_message()
  158. # print format (as attachment also - for text-only clients)
  159. self.email.add_attachment(self.dn.replace(' ','').replace('/','-') + '.html', self.body)
  160. # attachments
  161. # self.with_attachments comes from http form variables
  162. # i.e. with_attachments=1
  163. if cint(self.with_attachments):
  164. for a in self.set_attachments():
  165. a and self.email.attach_file(a.split(',')[1])
  166. # cc
  167. if self.cc:
  168. self.email.cc = [self.cc]
  169. self.email.send()
  170. self.make_communication()
  171. webnotes.msgprint('Sent')