Custom exception in mail.
authorJonathan Sandoval <jsandoval@utp.edu.co>
Fri, 8 Apr 2016 18:12:21 +0000 (13:12 -0500)
committerJonathan Sandoval <jsandoval@utp.edu.co>
Fri, 8 Apr 2016 18:12:21 +0000 (13:12 -0500)
mediagoblin/tools/mail.py

index c11e392bc31ff05bfe7fe4bb3dc32969c5e174a4..8161a324038c4f86743bb113222c6ce2efe49de7 100644 (file)
@@ -16,6 +16,8 @@
 
 from __future__ import print_function, unicode_literals
 
+import socket
+import logging
 import six
 import smtplib
 import sys
@@ -54,6 +56,14 @@ EMAIL_TEST_INBOX = []
 EMAIL_TEST_MBOX_INBOX = []
 
 
+class MailError(Exception):
+    """ General exception for mail errors """
+
+
+class NoSMTPServerError(MailError):
+    pass
+
+
 class FakeMhost(object):
     """
     Just a fake mail host so we can capture and test messages
@@ -101,13 +111,27 @@ def send_email(from_addr, to_addrs, subject, message_body):
         else:
             smtp_init = smtplib.SMTP
 
-        mhost = smtp_init(
-            mg_globals.app_config['email_smtp_host'],
-            mg_globals.app_config['email_smtp_port'])
+        try:
+            mhost = smtp_init(
+                mg_globals.app_config['email_smtp_host'],
+                mg_globals.app_config['email_smtp_port'])
+        except socket.error:
+            error_message = "Couldn't contact mail server on <{}>:<{}>".format(
+                mg_globals.app_config['email_smtp_host'],
+                mg_globals.app_config['email_smtp_port'])
+            logging.debug(error_message)
+            raise NoSMTPServerError(error_message)
 
         # SMTP.__init__ Issues SMTP.connect implicitly if host
         if not mg_globals.app_config['email_smtp_host']:  # e.g. host = ''
-            mhost.connect()  # We SMTP.connect explicitly
+            try:
+                mhost.connect()  # We SMTP.connect explicitly
+            except socket.error:
+                error_message = "Couldn't contact mail server on <{}>:<{}>".format(
+                    mg_globals.app_config['email_smtp_host'],
+                    mg_globals.app_config['email_smtp_port'])
+                logging.debug(error_message)
+                raise NoSMTPServerError(error_message)
 
         try:
             mhost.starttls()