You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

325 lines
9.9 KiB

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