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.
 
 
 
 
 
 

326 rader
10 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, (r.strip() for r in 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_html(self, message, text_content = None):
  63. """Attach message in the html portion of multipart/alternative"""
  64. message = message + self.get_footer()
  65. # this is the first html part of a multi-part message,
  66. # convert to text well
  67. if not self.html_set:
  68. if text_content:
  69. self.set_text(text_content)
  70. else:
  71. self.set_html_as_text(message)
  72. self.set_part_html(message)
  73. self.html_set = True
  74. def set_text(self, message):
  75. """
  76. Attach message in the text portion of multipart/alternative
  77. """
  78. from email.mime.text import MIMEText
  79. part = MIMEText(message.encode('utf-8'), 'plain', 'utf-8')
  80. self.msg_multipart.attach(part)
  81. def set_part_html(self, message):
  82. from email.mime.text import MIMEText
  83. part = MIMEText(message.encode('utf-8'), 'html', 'utf-8')
  84. self.msg_multipart.attach(part)
  85. def set_html_as_text(self, html):
  86. """return html2text"""
  87. import HTMLParser
  88. from webnotes.utils.email_lib.html2text import html2text
  89. try:
  90. self.set_text(html2text(html))
  91. except HTMLParser.HTMLParseError:
  92. pass
  93. def set_message(self, message, mime_type='text/html', as_attachment=0, filename='attachment.html'):
  94. """Append the message with MIME content to the root node (as attachment)"""
  95. from email.mime.text import MIMEText
  96. maintype, subtype = mime_type.split('/')
  97. part = MIMEText(message, _subtype = subtype)
  98. if as_attachment:
  99. part.add_header('Content-Disposition', 'attachment', filename=filename)
  100. self.msg_root.attach(part)
  101. def get_footer(self):
  102. """append a footer (signature)"""
  103. import startup
  104. footer = ""
  105. # if self.sender == webnotes.session.user:
  106. # signature = webnotes.conn.get_value("Profile", self.sender, "email_signature") or ""
  107. # if signature and (not "<br>" in signature) and (not "<p" in signature) \
  108. # and not "<div" in signature:
  109. # signature = signature.replace("\n", "<br>\n")
  110. # footer = signature
  111. footer += webnotes.conn.get_value('Control Panel',None,'mail_footer') or ''
  112. footer += getattr(startup, 'mail_footer', '')
  113. return footer
  114. def attach_file(self, n):
  115. """attach a file from the `FileData` table"""
  116. from webnotes.utils.file_manager import get_file
  117. res = get_file(n)
  118. if not res:
  119. return
  120. self.add_attachment(res[0], res[1])
  121. def add_attachment(self, fname, fcontent, content_type=None):
  122. """add attachment"""
  123. from email.mime.audio import MIMEAudio
  124. from email.mime.base import MIMEBase
  125. from email.mime.image import MIMEImage
  126. from email.mime.text import MIMEText
  127. import mimetypes
  128. if not content_type:
  129. content_type, encoding = mimetypes.guess_type(fname)
  130. if content_type is None:
  131. # No guess could be made, or the file is encoded (compressed), so
  132. # use a generic bag-of-bits type.
  133. content_type = 'application/octet-stream'
  134. maintype, subtype = content_type.split('/', 1)
  135. if maintype == 'text':
  136. # Note: we should handle calculating the charset
  137. part = MIMEText(fcontent, _subtype=subtype, _charset='utf-8')
  138. elif maintype == 'image':
  139. part = MIMEImage(fcontent, _subtype=subtype)
  140. elif maintype == 'audio':
  141. part = MIMEAudio(fcontent, _subtype=subtype)
  142. else:
  143. part = MIMEBase(maintype, subtype)
  144. part.set_payload(fcontent)
  145. # Encode the payload using Base64
  146. from email import encoders
  147. encoders.encode_base64(part)
  148. # Set the filename parameter
  149. if fname:
  150. part.add_header(b'Content-Disposition',
  151. ("attachment; filename=%s" % fname).encode('utf-8'))
  152. self.msg_root.attach(part)
  153. def validate(self):
  154. """validate the email ids"""
  155. from webnotes.utils import validate_email_add, extract_email_id
  156. def _validate(email):
  157. """validate an email field"""
  158. if email:
  159. if not validate_email_add(email):
  160. # try extracting the email part and set as sender
  161. new_email = extract_email_id(email)
  162. if not (new_email and validate_email_add(new_email)):
  163. webnotes.msgprint("%s is not a valid email id" % email,
  164. raise_exception = 1)
  165. email = new_email
  166. return email
  167. if not self.sender:
  168. # TODO: remove erpnext id
  169. self.sender = webnotes.conn.get_value('Email Settings', None,
  170. 'auto_email_id') or getattr(conf, 'auto_email_id')
  171. self.sender = _validate(self.sender)
  172. self.reply_to = _validate(self.reply_to)
  173. for e in self.recipients + (self.cc or []):
  174. _validate(e.strip())
  175. def make(self):
  176. """build into msg_root"""
  177. self.msg_root['Subject'] = self.subject.encode("utf-8")
  178. self.msg_root['From'] = self.sender.encode("utf-8")
  179. self.msg_root['To'] = ', '.join([r.strip() for r in self.recipients]).encode("utf-8")
  180. if self.reply_to and self.reply_to != self.sender:
  181. self.msg_root['Reply-To'] = self.reply_to.encode("utf-8")
  182. if self.cc:
  183. self.msg_root['CC'] = ', '.join([r.strip() for r in self.cc]).encode("utf-8")
  184. def as_string(self):
  185. """validate, build message and convert to string"""
  186. self.validate()
  187. self.make()
  188. return self.msg_root.as_string()
  189. def send(self, as_bulk=False):
  190. """send the message or add it to Outbox Email"""
  191. import smtplib
  192. try:
  193. SMTPServer().sess.sendmail(self.sender, self.recipients + (self.cc or []),
  194. self.as_string())
  195. except smtplib.SMTPSenderRefused, e:
  196. webnotes.msgprint("""Invalid Outgoing Mail Server's Login Id or Password. \
  197. Please rectify and try again.""",
  198. raise_exception=webnotes.OutgoingEmailError)
  199. class SMTPServer:
  200. def __init__(self, login=None, password=None, server=None, port=None, use_ssl=None):
  201. import webnotes.model.doc
  202. from webnotes.utils import cint
  203. # get defaults from control panel
  204. es = webnotes.model.doc.Document('Email Settings','Email Settings')
  205. self._sess = None
  206. if server:
  207. self.server = server
  208. self.port = port
  209. self.use_ssl = cint(use_ssl)
  210. self.login = login
  211. self.password = password
  212. elif es.outgoing_mail_server:
  213. self.server = es.outgoing_mail_server
  214. self.port = es.mail_port
  215. self.use_ssl = cint(es.use_ssl)
  216. self.login = es.mail_login
  217. self.password = es.mail_password
  218. else:
  219. self.server = getattr(conf, "mail_server", "")
  220. self.port = getattr(conf, "mail_port", None)
  221. self.use_ssl = cint(getattr(conf, "use_ssl", 0))
  222. self.login = getattr(conf, "mail_login", "")
  223. self.password = getattr(conf, "mail_password", "")
  224. @property
  225. def sess(self):
  226. """get session"""
  227. if self._sess:
  228. return self._sess
  229. from webnotes.utils import cint
  230. import smtplib
  231. import _socket
  232. # check if email server specified
  233. if not self.server:
  234. err_msg = 'Outgoing Mail Server not specified'
  235. webnotes.msgprint(err_msg)
  236. raise webnotes.OutgoingEmailError, err_msg
  237. try:
  238. if self.use_ssl and not self.port:
  239. self.port = 587
  240. self._sess = smtplib.SMTP((self.server or "").encode('utf-8'),
  241. cint(self.port) or None)
  242. if not self._sess:
  243. err_msg = 'Could not connect to outgoing email server'
  244. webnotes.msgprint(err_msg)
  245. raise webnotes.OutgoingEmailError, err_msg
  246. if self.use_ssl:
  247. self._sess.ehlo()
  248. self._sess.starttls()
  249. self._sess.ehlo()
  250. if self.login:
  251. ret = self._sess.login((self.login or "").encode('utf-8'),
  252. (self.password or "").encode('utf-8'))
  253. # check if logged correctly
  254. if ret[0]!=235:
  255. msgprint(ret[1])
  256. raise webnotes.OutgoingEmailError, ret[1]
  257. return self._sess
  258. except _socket.error, e:
  259. # Invalid mail server -- due to refusing connection
  260. webnotes.msgprint('Invalid Outgoing Mail Server or Port. Please rectify and try again.')
  261. raise webnotes.OutgoingEmailError, e
  262. except smtplib.SMTPAuthenticationError, e:
  263. webnotes.msgprint("Invalid Outgoing Mail Server's Login Id or Password. \
  264. Please rectify and try again.")
  265. raise webnotes.OutgoingEmailError, e
  266. except smtplib.SMTPException, e:
  267. webnotes.msgprint('There is something wrong with your Outgoing Mail Settings. \
  268. Please contact us at support@erpnext.com')
  269. raise webnotes.OutgoingEmailError, e