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

325 řádky
10 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):
  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)
  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):
  44. """Attach message in the html portion of multipart/alternative"""
  45. message = message + self.get_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):
  83. """append a footer (signature)"""
  84. import startup
  85. footer = ""
  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, extract_email_id
  133. def _validate(email):
  134. """validate an email field"""
  135. if email:
  136. if "," in email:
  137. email = email.split(",")[-1]
  138. if not validate_email_add(email):
  139. # try extracting the email part and set as sender
  140. new_email = extract_email_id(email)
  141. if not (new_email and validate_email_add(new_email)):
  142. webnotes.msgprint("%s is not a valid email id" % email,
  143. raise_exception = 1)
  144. email = new_email
  145. return email
  146. if not self.sender:
  147. self.sender = webnotes.conn.get_value('Email Settings', None,
  148. 'auto_email_id') or getattr(conf, 'auto_email_id', None)
  149. if not self.sender:
  150. webnotes.msgprint("""Please specify 'Auto Email Id' \
  151. in Setup > Email Settings""")
  152. if not hasattr(conf, "expires_on"):
  153. webnotes.msgprint("""Alternatively, \
  154. you can also specify 'auto_email_id' in conf.py""")
  155. raise webnotes.ValidationError
  156. self.sender = _validate(self.sender)
  157. self.reply_to = _validate(self.reply_to)
  158. for e in self.recipients + (self.cc or []):
  159. _validate(e.strip())
  160. def make(self):
  161. """build into msg_root"""
  162. self.msg_root['Subject'] = self.subject.encode("utf-8")
  163. self.msg_root['From'] = self.sender.encode("utf-8")
  164. self.msg_root['To'] = ', '.join([r.strip() for r in self.recipients]).encode("utf-8")
  165. if self.reply_to and self.reply_to != self.sender:
  166. self.msg_root['Reply-To'] = self.reply_to.encode("utf-8")
  167. if self.cc:
  168. self.msg_root['CC'] = ', '.join([r.strip() for r in self.cc]).encode("utf-8")
  169. def as_string(self):
  170. """validate, build message and convert to string"""
  171. self.validate()
  172. self.make()
  173. return self.msg_root.as_string()
  174. def send(self, as_bulk=False):
  175. """send the message or add it to Outbox Email"""
  176. if webnotes.mute_emails or getattr(conf, "mute_emails", False):
  177. webnotes.msgprint("Emails are muted")
  178. return
  179. import smtplib
  180. try:
  181. smtpserver = SMTPServer()
  182. if hasattr(smtpserver, "always_use_login_id_as_sender") and cint(smtpserver.always_use_login_id_as_sender):
  183. self.sender = smtpserver.login
  184. smtpserver.sess.sendmail(self.sender, self.recipients + (self.cc or []),
  185. self.as_string())
  186. except smtplib.SMTPSenderRefused:
  187. webnotes.msgprint("""Invalid Outgoing Mail Server's Login Id or Password. \
  188. Please rectify and try again.""",
  189. raise_exception=webnotes.OutgoingEmailError)
  190. except smtplib.SMTPRecipientsRefused:
  191. webnotes.msgprint("""Invalid Recipient (To) Email Address. \
  192. Please rectify and try again.""",
  193. raise_exception=webnotes.OutgoingEmailError)
  194. class SMTPServer:
  195. def __init__(self, login=None, password=None, server=None, port=None, use_ssl=None):
  196. import webnotes.model.doc
  197. from webnotes.utils import cint
  198. # get defaults from control panel
  199. es = webnotes.model.doc.Document('Email Settings','Email Settings')
  200. self._sess = None
  201. if server:
  202. self.server = server
  203. self.port = port
  204. self.use_ssl = cint(use_ssl)
  205. self.login = login
  206. self.password = password
  207. elif es.outgoing_mail_server:
  208. self.server = es.outgoing_mail_server
  209. self.port = es.mail_port
  210. self.use_ssl = cint(es.use_ssl)
  211. self.login = es.mail_login
  212. self.password = es.mail_password
  213. self.always_use_login_id_as_sender = es.always_use_login_id_as_sender
  214. else:
  215. self.server = getattr(conf, "mail_server", "")
  216. self.port = getattr(conf, "mail_port", None)
  217. self.use_ssl = cint(getattr(conf, "use_ssl", 0))
  218. self.login = getattr(conf, "mail_login", "")
  219. self.password = getattr(conf, "mail_password", "")
  220. @property
  221. def sess(self):
  222. """get session"""
  223. if self._sess:
  224. return self._sess
  225. from webnotes.utils import cint
  226. import smtplib
  227. import _socket
  228. # check if email server specified
  229. if not self.server:
  230. err_msg = 'Outgoing Mail Server not specified'
  231. webnotes.msgprint(err_msg)
  232. raise webnotes.OutgoingEmailError, err_msg
  233. try:
  234. if self.use_ssl and not self.port:
  235. self.port = 587
  236. self._sess = smtplib.SMTP((self.server or "").encode('utf-8'),
  237. cint(self.port) or None)
  238. if not self._sess:
  239. err_msg = 'Could not connect to outgoing email server'
  240. webnotes.msgprint(err_msg)
  241. raise webnotes.OutgoingEmailError, err_msg
  242. if self.use_ssl:
  243. self._sess.ehlo()
  244. self._sess.starttls()
  245. self._sess.ehlo()
  246. if self.login:
  247. ret = self._sess.login((self.login or "").encode('utf-8'),
  248. (self.password or "").encode('utf-8'))
  249. # check if logged correctly
  250. if ret[0]!=235:
  251. msgprint(ret[1])
  252. raise webnotes.OutgoingEmailError, ret[1]
  253. return self._sess
  254. except _socket.error, e:
  255. # Invalid mail server -- due to refusing connection
  256. webnotes.msgprint('Invalid Outgoing Mail Server or Port. Please rectify and try again.')
  257. raise webnotes.OutgoingEmailError, e
  258. except smtplib.SMTPAuthenticationError, e:
  259. webnotes.msgprint("Invalid Outgoing Mail Server's Login Id or Password. \
  260. Please rectify and try again.")
  261. raise webnotes.OutgoingEmailError, e
  262. except smtplib.SMTPException, e:
  263. webnotes.msgprint('There is something wrong with your Outgoing Mail Settings. \
  264. Please contact us at support@erpnext.com')
  265. raise webnotes.OutgoingEmailError, e