Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

340 řádky
11 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. footer += webnotes.conn.get_value('Control Panel',None,'mail_footer') or ''
  106. footer += getattr(startup, 'mail_footer', '')
  107. return footer
  108. def attach_file(self, n):
  109. """attach a file from the `FileData` table"""
  110. from webnotes.utils.file_manager import get_file
  111. res = get_file(n)
  112. if not res:
  113. return
  114. self.add_attachment(res[0], res[1])
  115. def add_attachment(self, fname, fcontent, content_type=None):
  116. """add attachment"""
  117. from email.mime.audio import MIMEAudio
  118. from email.mime.base import MIMEBase
  119. from email.mime.image import MIMEImage
  120. from email.mime.text import MIMEText
  121. import mimetypes
  122. if not content_type:
  123. content_type, encoding = mimetypes.guess_type(fname)
  124. if content_type is None:
  125. # No guess could be made, or the file is encoded (compressed), so
  126. # use a generic bag-of-bits type.
  127. content_type = 'application/octet-stream'
  128. maintype, subtype = content_type.split('/', 1)
  129. if maintype == 'text':
  130. # Note: we should handle calculating the charset
  131. if isinstance(fcontent, unicode):
  132. fcontent = fcontent.encode("utf-8")
  133. part = MIMEText(fcontent, _subtype=subtype, _charset="utf-8")
  134. elif maintype == 'image':
  135. part = MIMEImage(fcontent, _subtype=subtype)
  136. elif maintype == 'audio':
  137. part = MIMEAudio(fcontent, _subtype=subtype)
  138. else:
  139. part = MIMEBase(maintype, subtype)
  140. part.set_payload(fcontent)
  141. # Encode the payload using Base64
  142. from email import encoders
  143. encoders.encode_base64(part)
  144. # Set the filename parameter
  145. if fname:
  146. part.add_header(b'Content-Disposition',
  147. ("attachment; filename=%s" % fname).encode('utf-8'))
  148. self.msg_root.attach(part)
  149. def validate(self):
  150. """validate the email ids"""
  151. from webnotes.utils import validate_email_add, extract_email_id
  152. def _validate(email):
  153. """validate an email field"""
  154. if email:
  155. if "," in email:
  156. email = email.split(",")[-1]
  157. if not validate_email_add(email):
  158. # try extracting the email part and set as sender
  159. new_email = extract_email_id(email)
  160. if not (new_email and validate_email_add(new_email)):
  161. webnotes.msgprint("%s is not a valid email id" % email,
  162. raise_exception = 1)
  163. email = new_email
  164. return email
  165. if not self.sender:
  166. self.sender = webnotes.conn.get_value('Email Settings', None,
  167. 'auto_email_id') or getattr(conf, 'auto_email_id', None)
  168. if not self.sender:
  169. webnotes.msgprint("""Please specify 'Auto Email Id' \
  170. in Setup > Email Settings""")
  171. if not hasattr(conf, "expires_on"):
  172. webnotes.msgprint("""Alternatively, \
  173. you can also specify 'auto_email_id' in conf.py""")
  174. raise webnotes.ValidationError
  175. self.sender = _validate(self.sender)
  176. self.reply_to = _validate(self.reply_to)
  177. for e in self.recipients + (self.cc or []):
  178. _validate(e.strip())
  179. def make(self):
  180. """build into msg_root"""
  181. self.msg_root['Subject'] = self.subject.encode("utf-8")
  182. self.msg_root['From'] = self.sender.encode("utf-8")
  183. self.msg_root['To'] = ', '.join([r.strip() for r in self.recipients]).encode("utf-8")
  184. if self.reply_to and self.reply_to != self.sender:
  185. self.msg_root['Reply-To'] = self.reply_to.encode("utf-8")
  186. if self.cc:
  187. self.msg_root['CC'] = ', '.join([r.strip() for r in self.cc]).encode("utf-8")
  188. def as_string(self):
  189. """validate, build message and convert to string"""
  190. self.validate()
  191. self.make()
  192. return self.msg_root.as_string()
  193. def send(self, as_bulk=False):
  194. """send the message or add it to Outbox Email"""
  195. if webnotes.mute_emails or getattr(conf, "mute_emails", False):
  196. webnotes.msgprint("Emails are muted")
  197. return
  198. import smtplib
  199. try:
  200. smtpserver = SMTPServer()
  201. if hasattr(smtpserver, "always_use_login_id_as_sender") and smtpserver.always_use_login_id_as_sender:
  202. self.sender = smtpserver.login
  203. smtpserver.sess.sendmail(self.sender, self.recipients + (self.cc or []),
  204. self.as_string())
  205. except smtplib.SMTPSenderRefused, e:
  206. webnotes.msgprint("""Invalid Outgoing Mail Server's Login Id or Password. \
  207. Please rectify and try again.""",
  208. raise_exception=webnotes.OutgoingEmailError)
  209. class SMTPServer:
  210. def __init__(self, login=None, password=None, server=None, port=None, use_ssl=None):
  211. import webnotes.model.doc
  212. from webnotes.utils import cint
  213. # get defaults from control panel
  214. es = webnotes.model.doc.Document('Email Settings','Email Settings')
  215. self._sess = None
  216. if server:
  217. self.server = server
  218. self.port = port
  219. self.use_ssl = cint(use_ssl)
  220. self.login = login
  221. self.password = password
  222. elif es.outgoing_mail_server:
  223. self.server = es.outgoing_mail_server
  224. self.port = es.mail_port
  225. self.use_ssl = cint(es.use_ssl)
  226. self.login = es.mail_login
  227. self.password = es.mail_password
  228. self.always_use_login_id_as_sender = es.always_use_login_id_as_sender
  229. else:
  230. self.server = getattr(conf, "mail_server", "")
  231. self.port = getattr(conf, "mail_port", None)
  232. self.use_ssl = cint(getattr(conf, "use_ssl", 0))
  233. self.login = getattr(conf, "mail_login", "")
  234. self.password = getattr(conf, "mail_password", "")
  235. @property
  236. def sess(self):
  237. """get session"""
  238. if self._sess:
  239. return self._sess
  240. from webnotes.utils import cint
  241. import smtplib
  242. import _socket
  243. # check if email server specified
  244. if not self.server:
  245. err_msg = 'Outgoing Mail Server not specified'
  246. webnotes.msgprint(err_msg)
  247. raise webnotes.OutgoingEmailError, err_msg
  248. try:
  249. if self.use_ssl and not self.port:
  250. self.port = 587
  251. self._sess = smtplib.SMTP((self.server or "").encode('utf-8'),
  252. cint(self.port) or None)
  253. if not self._sess:
  254. err_msg = 'Could not connect to outgoing email server'
  255. webnotes.msgprint(err_msg)
  256. raise webnotes.OutgoingEmailError, err_msg
  257. if self.use_ssl:
  258. self._sess.ehlo()
  259. self._sess.starttls()
  260. self._sess.ehlo()
  261. if self.login:
  262. ret = self._sess.login((self.login or "").encode('utf-8'),
  263. (self.password or "").encode('utf-8'))
  264. # check if logged correctly
  265. if ret[0]!=235:
  266. msgprint(ret[1])
  267. raise webnotes.OutgoingEmailError, ret[1]
  268. return self._sess
  269. except _socket.error, e:
  270. # Invalid mail server -- due to refusing connection
  271. webnotes.msgprint('Invalid Outgoing Mail Server or Port. Please rectify and try again.')
  272. raise webnotes.OutgoingEmailError, e
  273. except smtplib.SMTPAuthenticationError, e:
  274. webnotes.msgprint("Invalid Outgoing Mail Server's Login Id or Password. \
  275. Please rectify and try again.")
  276. raise webnotes.OutgoingEmailError, e
  277. except smtplib.SMTPException, e:
  278. webnotes.msgprint('There is something wrong with your Outgoing Mail Settings. \
  279. Please contact us at support@erpnext.com')
  280. raise webnotes.OutgoingEmailError, e