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.
 
 
 
 
 
 

283 rader
9.4 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. """
  24. Sends email via outgoing server specified in "Control Panel"
  25. Allows easy adding of Attachments of "File" objects
  26. """
  27. import webnotes
  28. import conf
  29. from webnotes import msgprint
  30. import email
  31. def get_email(recipients, sender='', msg='', subject='[No Subject]', text_content = None):
  32. """send an html email as multipart with attachments and all"""
  33. email = EMail(sender, recipients, subject)
  34. if (not '<br>' in msg) and (not '<p>' in msg) and (not '<div' in msg):
  35. msg = msg.replace('\n', '<br>')
  36. email.set_html(msg, text_content)
  37. return email
  38. class EMail:
  39. """
  40. Wrapper on the email module. Email object represents emails to be sent to the client.
  41. Also provides a clean way to add binary `FileData` attachments
  42. Also sets all messages as multipart/alternative for cleaner reading in text-only clients
  43. """
  44. def __init__(self, sender='', recipients=[], subject='', alternative=0, reply_to=None):
  45. from email.mime.multipart import MIMEMultipart
  46. from email import Charset
  47. Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
  48. if isinstance(recipients, basestring):
  49. recipients = recipients.replace(';', ',').replace('\n', '')
  50. recipients = recipients.split(',')
  51. # remove null
  52. recipients = filter(None, recipients)
  53. self.sender = sender
  54. self.reply_to = reply_to or sender
  55. self.recipients = recipients
  56. self.subject = subject
  57. self.msg_root = MIMEMultipart('mixed')
  58. self.msg_multipart = MIMEMultipart('alternative')
  59. self.msg_root.attach(self.msg_multipart)
  60. self.cc = []
  61. self.html_set = False
  62. def set_text(self, message):
  63. """
  64. Attach message in the text portion of multipart/alternative
  65. """
  66. from email.mime.text import MIMEText
  67. part = MIMEText(message.encode('utf-8'), 'plain', 'utf-8')
  68. self.msg_multipart.attach(part)
  69. def set_html(self, message, text_content = None):
  70. """Attach message in the html portion of multipart/alternative"""
  71. from email.mime.text import MIMEText
  72. message = message + self.get_footer()
  73. # this is the first html part of a multi-part message,
  74. # convert to text well
  75. if not self.html_set:
  76. if text_content:
  77. self.set_text(text_content)
  78. else:
  79. self.set_html_text(message)
  80. part = MIMEText(message.encode('utf-8'), 'html', 'utf-8')
  81. self.msg_multipart.attach(part)
  82. self.html_set = True
  83. def set_html_text(self, html):
  84. """return html2text"""
  85. import HTMLParser
  86. from webnotes.utils.email_lib.html2text import html2text
  87. try:
  88. self.set_text(html2text(html))
  89. except HTMLParser.HTMLParseError:
  90. pass
  91. def set_message(self, message, mime_type='text/html', as_attachment=0, filename='attachment.html'):
  92. """Append the message with MIME content to the root node (as attachment)"""
  93. from email.mime.text import MIMEText
  94. maintype, subtype = mime_type.split('/')
  95. part = MIMEText(message, _subtype = subtype)
  96. if as_attachment:
  97. part.add_header('Content-Disposition', 'attachment', filename=filename)
  98. self.msg_root.attach(part)
  99. def get_footer(self):
  100. """append a footer"""
  101. import startup
  102. footer = webnotes.conn.get_value('Control Panel',None,'mail_footer') or ''
  103. footer += getattr(startup, 'mail_footer', '')
  104. return footer
  105. def attach_file(self, n):
  106. """attach a file from the `FileData` table"""
  107. from webnotes.utils.file_manager import get_file
  108. res = get_file(n)
  109. if not res:
  110. return
  111. self.add_attachment(res[0], res[1])
  112. def add_attachment(self, fname, fcontent, content_type=None):
  113. """add attachment"""
  114. from email.mime.audio import MIMEAudio
  115. from email.mime.base import MIMEBase
  116. from email.mime.image import MIMEImage
  117. from email.mime.text import MIMEText
  118. import mimetypes
  119. if not content_type:
  120. content_type, encoding = mimetypes.guess_type(fname)
  121. if content_type is None:
  122. # No guess could be made, or the file is encoded (compressed), so
  123. # use a generic bag-of-bits type.
  124. content_type = 'application/octet-stream'
  125. maintype, subtype = content_type.split('/', 1)
  126. if maintype == 'text':
  127. # Note: we should handle calculating the charset
  128. part = MIMEText(fcontent, _subtype=subtype, _charset='utf-8')
  129. elif maintype == 'image':
  130. part = MIMEImage(fcontent, _subtype=subtype)
  131. elif maintype == 'audio':
  132. part = MIMEAudio(fcontent, _subtype=subtype)
  133. else:
  134. part = MIMEBase(maintype, subtype)
  135. part.set_payload(fcontent)
  136. # Encode the payload using Base64
  137. from email import encoders
  138. encoders.encode_base64(part)
  139. # Set the filename parameter
  140. if fname:
  141. part.add_header(b'Content-Disposition',
  142. ("attachment; filename=%s" % fname).encode('utf-8'))
  143. self.msg_root.attach(part)
  144. def validate(self):
  145. """validate the email ids"""
  146. if not self.sender:
  147. self.sender = webnotes.conn.get_value('Email Settings', None, 'auto_email_id') \
  148. or getattr(conf, 'auto_email_id', 'ERPNext Notification <notification@erpnext.com>')
  149. from webnotes.utils import validate_email_add
  150. # validate ids
  151. if self.sender and (not validate_email_add(self.sender)):
  152. webnotes.msgprint("%s is not a valid email id" % self.sender, raise_exception = 1)
  153. if self.reply_to and (not validate_email_add(self.reply_to)):
  154. webnotes.msgprint("%s is not a valid email id" % self.reply_to, raise_exception = 1)
  155. for e in self.recipients + (self.cc or []):
  156. if not validate_email_add(e):
  157. webnotes.msgprint("%s is not a valid email id" % e, raise_exception = 1)
  158. def make(self):
  159. """build into msg_root"""
  160. self.msg_root['Subject'] = self.subject.encode("utf-8")
  161. self.msg_root['From'] = self.sender.encode("utf-8")
  162. self.msg_root['To'] = ', '.join([r.strip() for r in self.recipients]).encode("utf-8")
  163. if self.reply_to and self.reply_to != self.sender:
  164. self.msg_root['Reply-To'] = self.reply_to.encode("utf-8")
  165. if self.cc:
  166. self.msg_root['CC'] = ', '.join([r.strip() for r in self.cc]).encode("utf-8")
  167. def as_string(self):
  168. """validate, build message and convert to string"""
  169. self.validate()
  170. self.make()
  171. return self.msg_root.as_string()
  172. def send(self, as_bulk=False):
  173. """send the message or add it to Outbox Email"""
  174. SMTPServer().sess.sendmail(self.sender, self.recipients + (self.cc or []),
  175. self.as_string())
  176. class SMTPServer:
  177. def __init__(self, login=None, password=None, server=None, port=None, use_ssl=None):
  178. import webnotes.model.doc
  179. from webnotes.utils import cint
  180. # get defaults from control panel
  181. es = webnotes.model.doc.Document('Email Settings','Email Settings')
  182. self.server = server or es.outgoing_mail_server \
  183. or getattr(conf,'mail_server','')
  184. self.login = login or es.mail_login \
  185. or getattr(conf,'mail_login','')
  186. self.port = port or cint(es.mail_port) \
  187. or getattr(conf,'mail_port',None)
  188. self.password = password or es.mail_password \
  189. or getattr(conf,'mail_password','')
  190. self.use_ssl = use_ssl or cint(es.use_ssl) \
  191. or cint(getattr(conf, 'use_ssl', ''))
  192. self._sess = None
  193. @property
  194. def sess(self):
  195. """get session"""
  196. if self._sess:
  197. return self._sess
  198. from webnotes.utils import cint
  199. import smtplib
  200. import _socket
  201. # check if email server specified
  202. if not self.server:
  203. err_msg = 'Outgoing Mail Server not specified'
  204. webnotes.msgprint(err_msg)
  205. raise webnotes.OutgoingEmailError, err_msg
  206. try:
  207. self._sess = smtplib.SMTP(self.server.encode('utf-8'), cint(self.port) or None)
  208. if not self._sess:
  209. err_msg = 'Could not connect to outgoing email server'
  210. webnotes.msgprint(err_msg)
  211. raise webnotes.OutgoingEmailError, err_msg
  212. if self.use_ssl:
  213. self._sess.ehlo()
  214. self._sess.starttls()
  215. self._sess.ehlo()
  216. ret = self._sess.login(self.login.encode('utf-8'), self.password.encode('utf-8'))
  217. # check if logged correctly
  218. if ret[0]!=235:
  219. msgprint(ret[1])
  220. raise webnotes.OutgoingEmailError, ret[1]
  221. return self._sess
  222. except _socket.error, e:
  223. # Invalid mail server -- due to refusing connection
  224. webnotes.msgprint('Invalid Outgoing Mail Server or Port. Please rectify and try again.')
  225. raise webnotes.OutgoingEmailError, e
  226. except smtplib.SMTPAuthenticationError, e:
  227. webnotes.msgprint('Invalid Login Id or Mail Password. Please rectify and try again.')
  228. raise webnotes.OutgoingEmailError, e
  229. except smtplib.SMTPException, e:
  230. webnotes.msgprint('There is something wrong with your Outgoing Mail Settings. \
  231. Please contact us at support@erpnext.com')
  232. raise webnotes.OutgoingEmailError, e