def __init__(self, host='', port=0, proxy=None, local_hostname=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): self.timeout = timeout self.esmtp_features = {} # ------------------------------------------- self.proxy = proxy # ------------------------------------------- if host: (code, msg) = self.connect(host, port) if code != 220: raise smtplib.SMTPConnectError(code, msg) if local_hostname is not None: self.local_hostname = local_hostname else: fqdn = socket.getfqdn() if '.' in fqdn: self.local_hostname = fqdn else: addr = '127.0.0.1' try: addr = socket.gethostbyname(socket.gethostname()) except socket.gaierror: pass self.local_hostname = '[%s]' % addr
def test_send_via_smtp_incorrect_smtp_host(self): smtp_settings = { 'host': 'gmail.bla.bla', 'port': 123, 'email': '*****@*****.**', 'password': '******' } to_emails = ['*****@*****.**', '*****@*****.**', '*****@*****.**'] problems = {} with patch.object( smtplib.SMTP_SSL, 'connect', return_value=(123, 'side effect: SMTPConnectError') ) as mock_smtp_obj, \ patch.object( smtplib.SMTP_SSL, 'close', return_value=None ) as mock_smtp_obj_close: mock_smtp_obj = Mock() mock_smtp_obj.side_effect = smtplib.SMTPConnectError( 123, 'side effect: SMTPConnectError' ) with self.assertRaises(smtplib.SMTPConnectError): send_via_smtp(smtp_settings, to_emails, problems)
def send(self): """ Uses smtplib package to connect to provided smtp address and port, then send the message. Supports smtp password authentication. Logs sender, recipient, and attachment. """ session = smtplib.SMTP(self.SMTP_SERVER, self.SMTP_PORT) # the smtplib error is not very descriptive: "SMTPServerDisconnected: please run connect() first" if not self.SMTP_SERVER: raise smtplib.SMTPConnectError(code='', msg="No SMTP Server provided.") # allows for password on smtp if self.password: session.ehlo() session.starttls() session.ehlo() session.login(self.sender, self.password) session.sendmail(from_addr=self.sender, to_addrs=self.recipients, msg=self.msg.as_string()) logstr = """Email Sent: to -%s, from -%s, attached -%s.""" % ( self.recipients, self.sender, self.files) logstr = logstr.replace('\\', '').replace("'", '') rLog.info(logstr) session.quit()
def __init__(self, host=''): self.lmtp_features = {} self.esmtp_features = self.lmtp_features if host: (code, msg) = self.connect(host) if code != 220: raise smtplib.SMTPConnectError(code, msg)
async def init(self): if self._host: code, msg = await self.connect(self._host, self._port) if code != 220: self.close() raise smtplib.SMTPConnectError(code, msg) return
def test_expecting_SMTP_connection_error(self) -> None: check = UnitTestSmtpCredentials._create_mocked_method_raising( smtplib.SMTPConnectError(0, '')) status, message = UnitTestSmtpCredentials._run_mocked_check( self.test_expecting_SMTP_connection_error.__name__, check) self.assertEqual( (status, message), (False, smtpcheck.Messages.SMTP_CONNECTION_ERROR.value))
def test_connect_fail(self, connection_mock): connection_mock.return_value.open.side_effect = \ smtplib.SMTPConnectError("Blah", 101) result = toolkit.members.tasks.send_mailout( u"The \xa31 Subject!", u"The Body!\nThat will be $1, please\nTa!", None) self.assertEqual( result, (True, 0, "Failed to connect to SMTP server: ('Blah', 101)"))
def test_fallimento_connect(self, mock_smtp): """ In caso di fallimento durante il connect il messaggio viene rimesso in coda """ codici = (421, ) for codice in codici: msg = 'code {}'.format(codice) instance = mock_smtp.return_value instance.sendmail.side_effect = smtplib.SMTPConnectError( code=codice, msg=msg) self._invia_msg_singolo() self.assertEqual(Messaggio.in_coda().count(), 1) self._reset_coda()
def test_emailer_send_email_disconnect(self, mock_smtplib): """Test class method: Emailer.send_email() re-attempt login and send_email if it encounters smtplib.SMTPConnectError() during initial send of email. Validate smtplib.SMTP() and smtplib.SMTP.sendmail() are called twice. """ instance = mock_smtplib.return_value instance.sendmail.side_effect = smtplib.SMTPConnectError( 421, 'Cannot connect to SMTP server') test_emailer = Emailer(config=_make_credentials(), delay_login=True) with self.assertRaises(smtplib.SMTPConnectError): test_emailer.send_email('My test email', test_emailer._config.sender_email, '*****@*****.**') self.assertEqual(instance.sendmail.call_count, 2) self.assertEqual(mock_smtplib.call_count, 2)
def __init__(self, host='', port=0, local_hostname=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None): """Initialize a new instance. If specified, `host' is the name of the remote host to which to connect. If specified, `port' specifies the port to which to connect. By default, smtplib.SMTP_PORT is used. If a host is specified the connect method is called, and if it returns anything other than a success code an SMTPConnectError is raised. If specified, `local_hostname` is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found using socket.getfqdn(). The `source_address` parameter takes a 2-tuple (host, port) for the socket to bind to as its source address before connecting. If the host is '' and port is 0, the OS default behavior will be used. """ self._host = host self.timeout = timeout self.esmtp_features = {} self.source_address = source_address if host: (code, msg) = self.connect(host, port) if code != 220: raise smtplib.SMTPConnectError(code, msg) if local_hostname is not None: self.local_hostname = local_hostname else: # RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and # if that can't be calculated, that we should use a domain literal # instead (essentially an encoded IP address like [A.B.C.D]). fqdn = socket.getfqdn() if '.' in fqdn: self.local_hostname = fqdn else: # We can't find an fqdn hostname, so use a domain literal addr = '127.0.0.1' try: addr = socket.gethostbyname(socket.gethostname()) except socket.gaierror: pass self.local_hostname = '[%s]' % addr
def send_email(email_destino, password): email = EmailMessage() email['Subject'] = "Recuperacao de Password MuseuOnline Unilurio" email['From'] = '*****@*****.**' email['To'] = email_destino try: email.set_content( "Recuperacao do password, utilize o link: {}, para recuperar sua conta no Museu Online UniLurio" "\n\n!".format("facebook.com/" + password)) smtp = smtplib.SMTP(host="smtp.gmail.com", port=587) smtp.starttls() smtp.login("*****@*****.**", "#G!g!l+*12.") smtp.send_message(email) smtp.quit() except smtplib.SMTPConnectError: return smtplib.SMTPConnectError("123", "Conexao failed") except smtplib.SMTPAuthenticationError: return smtplib.SMTPAuthenticationError("124", "Erro de autenticacao") except smtplib.SMTPServerDisconnected: return smtplib.SMTPServerDisconnected except smtplib.SMTPDataError: return "Error" except smtplib.SMTPSenderRefused: return smtplib.SMTPSenderRefused("126", "Error send refused", email['To']) except smtplib.SMTPResponseException: return smtplib.SMTPResponseException("125", "Error not Respponse") except smtplib.SMTPNotSupportedError: return "error Not supported" except smtplib.SMTPException: return "ERRORR"
def test_40_notifies_again_after_smtp_error(self, mock_smtp, mock_run, mock_stderr): self.addUser(expire=23, mail=True) # refuse SMTP connection import smtplib mock_smtp.side_effect = smtplib.SMTPConnectError(42, 'Connection refused') # call tool one time rc = main(['-c', os.path.dirname(__file__) + "/password.conf"]) self.assertEqual(mock_stderr.getvalue(), "SMTP error: (42, 'Connection refused')\n") self.assertEqual(rc, 1) SMTP = mock_smtp.return_value self.assertEqual(SMTP.sendmail.call_count, 0) # 7 days and a bit later without SMTP problems mock_smtp.side_effect = None rc = main(['-c', os.path.dirname(__file__) + "/password.conf", '--time', ldap_time(hours=1)]) self.assertEqual(rc, 0) self.assertEqual(SMTP.sendmail.call_count, 2)
def send_messages(self, email_messages): """ Sends one or more EmailMessage objects and returns the number of email messages sent. """ if not email_messages: return 0 self._lock.acquire() try: new_conn_created = self.open() if not self.connection and self.fail_silently is False: raise smtplib.SMTPConnectError("Cannot send without a valid connection") num_sent = 0 for message in email_messages: num_sent += self.send(message) if new_conn_created: self.close() finally: self._lock.release() return num_sent
def login(self): if (self.smtp_port < 1): toks = self.smtp_server.split(':') self.smtp_server = toks[0] self.smtp_port = -1 if (len(toks) != 2) else -1 if ( not toks[-1].isdigit()) else int(toks[-1]) if (len(self.smtp_server) > 0) and (isinstance( self.smtp_port, int)) and (self.smtp_port > -1): print '(%s.%s) :: smtpServer=[%s], port=[%s], username=[%s], password=[%s]' % ( ObjectTypeName.typeName(self), misc.funcName(), self.smtp_server, self.smtp_port, self.smtp_username, self.smtp_password) try: self.mailServer = smtplib.SMTP(host=self.smtp_server, port=self.smtp_port) self.mailServer.set_debuglevel(self.debug) if (len(self.smtp_username) > 0) and (len(self.smtp_password) > 0): self.mailServer.login(self.smtp_username, self.smtp_password) except Exception as details: tbinfofile = StringIO.StringIO() traceback.print_exc(None, tbinfofile) tbinfofile.seek(0) tbinfo = tbinfofile.read() _msg = '(%s.%s) :: ERROR due to "%s"\n%s.' % ( ObjectTypeName.typeName(self), misc.funcName(), details, tbinfo) print >> sys.stderr, _msg raise smtplib.SMTPConnectError(_msg) self.log = self.logger else: _msg = '(%s.%s) :: WARNING :: Invalid SMTP Configuration that does not work, recommend checking your choices and attributes because something is wrong. smtpServer=[%s], port=[%s], username=[%s], password=[%s]' % ( ObjectTypeName.typeName(self), misc.funcName(), self.smtp_server, self.smtp_port, self.smtp_username, self.smtp_password) print >> sys.stderr, _msg raise ValueError(_msg)
def test_connect_failure(self, mock_error, mock_smtp): mock_smtp.side_effect = smtplib.SMTPConnectError(123, 'aww crap') mail._send_email('hello', 'stuff', '*****@*****.**') self.assertTrue(mock_error.called)
def __init__(self, host='', port=0, proxy_host=None, proxy_port=None, proxy_username=None, proxy_password=None, proxy_type=socks.HTTP, local_hostname=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None): """Initialize a new instance. If a host is specified the connect method is called, and if it returns anything other than a success code an SMTPConnectError is raised :param host: Hostname of SMTP server :type host: string :param port: Port of SMTP server, by default smtplib.SMTP_PORT is used :type port: int :param proxy_host: Hostname of proxy server :type proxy_host: string :param proxy_port: Port of proxy server, by default port for specified proxy type is used :type proxy_port: int :param proxy_username: Username of proxy server :type proxy_username: string :param proxy_password: Password of proxy server :type proxy_password: string :param proxy_type: Proxy type to use (see socks.PROXY_TYPES for details) :type proxy_type: int :param local_hostname: Local hostname is used as the FQDN of the local host for the HELO/EHLO command, if not specified the local hostname is found using socket.getfqdn() :type local_hostname: string :param timeout: Connection timeout :type timeout: int :param source_address: Host and port for the socket to bind to as its source address before connecting :type source_address: tuple """ self._host = host self.timeout = timeout self.esmtp_features = {} self.command_encoding = 'ascii' self.source_address = source_address if host: if proxy_host: (code, msg) = self.connect_proxy(proxy_host, proxy_port, proxy_type, proxy_username, proxy_password, host, port) else: (code, msg) = self.connect(host, port) if code != 220: raise smtplib.SMTPConnectError(code, msg) if local_hostname is not None: self.local_hostname = local_hostname else: # RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and # if that can't be calculated, that we should use a domain literal # instead (essentially an encoded IP address like [A.B.C.D]). fqdn = socket.getfqdn() if '.' in fqdn: self.local_hostname = fqdn else: # We can't find an fqdn hostname, so use a domain literal addr = '127.0.0.1' try: addr = socket.gethostbyname(socket.gethostname()) except socket.gaierror: pass self.local_hostname = '[%s]' % addr