Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

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