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ů.
 
 
 
 
 
 

321 řádky
9.9 KiB

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