def login(self, user, password): def encode_cram_md5(challenge, user, password): challenge = encode_base64.decodestring(challenge) response = user + " " + smtplib.hmac.HMAC(password, challenge).hexdigest() return encode_base64(response) def encode_plain(user, password): s = "\0%s\0%s" % (user, password) return encode_base64(s.encode('ascii'), eol='') AUTH_PLAIN = "PLAIN" AUTH_CRAM_MD5 = "CRAM-MD5" AUTH_LOGIN = "******" self.ehlo_or_helo_if_needed() if not self.has_extn("auth"): raise smtplib.SMTPException( "SMTP AUTH extension not supported by server.") authlist = self.esmtp_features["auth"].split() preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN] authmethod = None for method in preferred_auths: if method in authlist: authmethod = method break if authmethod == AUTH_LOGIN: (code, resp) = self.docmd("AUTH", "%s %s" % (AUTH_LOGIN, encode_base64(user))) if code != 334: raise smtplib.SMTPAuthenticationError(code, resp) (code, resp) = self.docmd(encode_base64(password)) elif authmethod == AUTH_PLAIN: temp_encode_plain = str(encode_plain(user, password)) temp_encode_plain = temp_encode_plain.replace("\n", "") (code, resp) = self.docmd("AUTH", AUTH_PLAIN + " " + temp_encode_plain) elif authmethod == AUTH_CRAM_MD5: (code, resp) = self.docmd("AUTH", AUTH_CRAM_MD5) if code == 503: return (code, resp) (code, resp) = self.docmd(encode_cram_md5(resp, user, password)) elif authmethod is None: raise smtplib.SMTPException( "No suitable authentication method found.") if code not in (235, 503): raise smtplib.SMTPAuthenticationError(code, resp) return (code, resp)
def _connect_to_exchange(self, smtp): code, response = smtp.ehlo() if code != SMTP_EHLO_OKAY: logging.error("Server did not respond as expected to EHLO command") raise smtplib.SMTPException( "Server did not respond as expected to EHLO command") sspiclient = sspi.ClientAuth('NTLM') # Generate the NTLM Type 1 message sec_buffer = None err, sec_buffer = sspiclient.authorize(sec_buffer) ntlm_message = asbase64(sec_buffer[0].Buffer) # Send the NTLM Type 1 message -- Authentication Request code, response = smtp.docmd("AUTH", "NTLM " + ntlm_message) # Verify the NTLM Type 2 response -- Challenge Message if code != SMTP_AUTH_CHALLENGE: logging.error( "Server did not respond as expected to NTLM negotiate message") raise smtplib.SMTPException( "Server did not respond as expected to NTLM negotiate message") # Generate the NTLM Type 3 message err, sec_buffer = sspiclient.authorize(base64.decodebytes(response)) ntlm_message = asbase64(sec_buffer[0].Buffer) # Send the NTLM Type 3 message -- Response Message code, response = smtp.docmd("", ntlm_message) if code != SMTP_AUTH_OKAY: logging.error("SMTPAuthenticationError") raise smtplib.SMTPAuthenticationError(code, response) # if this part is reached, the authentication was succesfull and emails can be sent. pass
def test_send_mail_AUTH_FAILURE(caplog): with patch('bote.Mailer._Mailer__send_starttls', side_effect=smtplib.SMTPAuthenticationError(123, 'foo')): mailer = bote.Mailer(false_but_valid_mail_settings) with pytest.raises(smtplib.SMTPAuthenticationError): mailer.send_mail('random subject', 'random content') assert "SMTP authentication failed" in caplog.text
def auth(self, mechanism, authobject, *, initial_response_ok=True): """Authentication command - requires response processing. 'mechanism' specifies which authentication mechanism is to be used - the valid values are those listed in the 'auth' element of 'esmtp_features'. 'authobject' must be a callable object taking a single argument: data = authobject(challenge) It will be called to process the server's challenge response; the challenge argument it is passed will be a bytes. It should return bytes data that will be base64 encoded and sent to the server. Keyword arguments: - initial_response_ok: Allow sending the RFC 4954 initial-response to the AUTH command, if the authentication methods supports it. """ # RFC 4954 allows auth methods to provide an initial response. Not all # methods support it. By definition, if they return something other # than None when challenge is None, then they do. See issue #15014. mechanism = mechanism.upper() initial_response = (authobject() if initial_response_ok else None) if initial_response is not None: response = smtplib.encode_base64(initial_response.encode('utf-8'), eol='') (code, resp) = self.docmd("AUTH", mechanism + " " + response) else: (code, resp) = self.docmd("AUTH", mechanism) # If server responds with a challenge, send the response. if code == 334: challenge = base64.decodebytes(resp) response = smtplib.encode_base64( authobject(challenge).encode('utf-8'), eol='') (code, resp) = self.docmd(response) if code in (235, 503): return (code, resp) raise smtplib.SMTPAuthenticationError(code, resp)
def test_server_authenticate(self): server = Mock() settings = EmailSettings() server.login = Mock() self.notifier._server_authenticate(server, settings) server.login.assert_not_called() settings.login = self.helper.real_login self.notifier._server_authenticate(server, settings) server.login.assert_not_called() settings.password = self.helper.real_password server2 = self.notifier._server_authenticate(server, settings) self.assertEqual(server, server2) server.login.assert_called_once_with(self.helper.real_login, self.helper.real_password) server.quit = Mock() server.login = Mock( side_effect=smtplib.SMTPAuthenticationError(3, "123")) with self.assertRaises(EmailException) as e: self.notifier._server_authenticate(server, settings) self.assertEqual(e.exception.code, 4) self.assertEqual(e.exception.message, "SMTP login: Invalid login or password") server.quit.assert_called_once_with()
def _login(self): """login to smtp server""" try: self._smtp.login(self._username, self._password) except Exception: raise smtplib.SMTPAuthenticationError( "Login to SMTP server failed, check your email address and/or password" )
def send_mail(*args, **kwargs): failed.append( CapturedEmail( message=kwargs["message"], recipient_list=kwargs["recipient_list"], ) ) raise smtplib.SMTPAuthenticationError(1, "beep boop bad password")
def test_send_with_credential(self, mock_smtp): record = dict(name='gmail', vendor='google', uid=self.test_uid, key='*****@*****.**', secret='darkweb1', settings_id=self.settings_id) self.authorize(username=self.admin_name, password=self.admin_pw) response = self.call_endpoint('/credential', 'post', data=record) self.assertEqual(response.status_code, 201) id = response.get_json()['id'] response = self.call_endpoint('/settings/%s' % self.settings_id, 'get') self.assertEqual(response.status_code, 200) settings = response.get_json() settings['smtp_credential_id'] = id settings.pop('created', None) settings.pop('modified', None) settings.pop('rbac', None) response = self.call_endpoint('/settings/%s' % self.settings_id, 'put', data=settings) self.assertEqual(response.status_code, 200) Messaging().send(frm=self.test_uid, to=self.adm_contact_id, template='moderator', list='test', message='best test rest') name, args, kwargs = mock_smtp.method_calls.pop(0) self.assertEqual(name, '().starttls') name, args, kwargs = mock_smtp.method_calls.pop(0) self.assertEqual(name, '().login') name, args, kwargs = mock_smtp.method_calls.pop(0) self.assertEqual(name, '().sendmail') self.assertEqual({}, kwargs) _from, _to, _body = args self.assertIn("List: test\n\nbest test rest", _body) mock_smtp.return_value.login.side_effect = ( smtplib.SMTPAuthenticationError(code=403, msg='unauthorized')) with self.assertRaises(APIcrudSendError) as ex: Messaging().send(frm=self.test_uid, to=self.adm_contact_id, template='moderator', list='test', message='bad credential') self.assertEqual(ex.exception.args, ("Credential problem: (403, 'unauthorized')", )) # this just restores settings to avoid conflict with other tests settings['smtp_credential_id'] = None response = self.call_endpoint('/settings/%s' % self.settings_id, 'put', data=settings) self.assertEqual(response.status_code, 200)
def test_expecting_SMTP_authentication_error(self) -> None: check = UnitTestSmtpCredentials._create_mocked_method_raising( smtplib.SMTPAuthenticationError(0, '')) status, message = UnitTestSmtpCredentials._run_mocked_check( self.test_expecting_SMTP_authentication_error.__name__, check) self.assertEqual( (status, message), (False, smtpcheck.Messages.SMTP_AUTHENTICATION_ERROR.value))
def test_emit_invalid_credentials(self, smtp_adapter): body = 'Anomalous network activity detected from notpead.exe process' smtp_adapter.logger = Mock(spec_set=Logger) with patch('smtplib.SMTP'): smtp_adapter._smtp.login.side_effect = smtplib.SMTPAuthenticationError(534, 'Invalid smtp credentials') smtp_adapter.emit(body, subject='Anomalous network activity detected') smtp_adapter.logger.error.assert_called_with('Invalid SMTP credentials for ' '[email protected] account') smtp_adapter._smtp.quit.assert_called_once()
def test_fallimento_autenticazione(self, mock_smtp): """ In caso di fallimento autenticazione il messaggio viene rimesso in coda """ self.assertEqual(Messaggio.in_coda().count(), 0) instance = mock_smtp.return_value instance.sendmail.side_effect = smtplib.SMTPAuthenticationError( code=530, msg='authentication error') self._invia_msg_singolo() self.assertEqual(Messaggio.in_coda().count(), 1)
def login(self, username, password): def encode_cram_md5(challenge, username, password): challenge = base64.decodebytes(challenge) response = username + " " + hmac.HMAC(password.encode('ascii'), challenge, 'md5').hexdigest() return encode_base64(response.encode('ascii'), eol="") def encode_plain(user, password): return encode_base64(("\0%s\0%s" % (user, password)).encode('ascii'), eol="") AUTH_PLAIN = "PLAIN" AUTH_CRAM_MD5 = "CRAM-MD5" AUTH_LOGIN = "******" yield self.ehlo_or_helo_if_needed() if not self.has_extn('auth'): raise smtplib.SMTPException("SMTP Auth extension not supported by server ") advertised_authlist = self.esmtp_features["auth"].split() preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN] authlist = [auth for auth in preferred_auths if auth in advertised_authlist] if not authlist: raise smtplib.SMTPException("No suitable authentication method found.") # Some servers advertise authentication methods they don't really # support, so if authentication fails, we continue until we've tried # all methods. for authmethod in authlist: if authmethod == AUTH_CRAM_MD5: (code, resp) = yield self.docmd(b'AUTH', AUTH_CRAM_MD5) if code == 334: (code, resp) =yield self.docmd(encode_cram_md5(resp, username, password).encode('ascii')) elif authmethod == AUTH_PLAIN: (code, resp) =yield self.docmd(b'AUTH', (AUTH_PLAIN + " " + encode_plain(username, password)).encode('ascii')) elif authmethod == AUTH_LOGIN: (code, resp) = yield self.docmd(b'AUTH', ("%s %s" % (AUTH_LOGIN, encode_base64(username.encode('ascii'), eol=''))).encode('ascii')) if code == 334: (code, resp) = yield self.docmd(encode_base64(password.encode('ascii'), eol='').encode('ascii')) # 235 == 'Authentication successful' # 503 == 'Error: already authenticated' if code in (235, 503): raise gen.Return((code, resp)) # We could not login sucessfully. Return result of last attempt. raise smtplib.SMTPAuthenticationError(code, resp)
def login(connection, user, password, *, initial_response_ok=True): # self.set_debuglevel(True) connection.ehlo_or_helo_if_needed() if not connection.has_extn("auth"): raise smtplib.SMTPNotSupportedError( "SMTP AUTH extension not supported by server.") connection.user, connection.password = user, password # Authentication methods the server claims to support advertised_authlist = connection.esmtp_features["auth"].split() if connection.auth_method not in advertised_authlist: raise smtplib.SMTPException( "No suitable authentication method found.") try: auth_object = _get_oauth2_object(self.user, user, self.provider) except ValueError as e: raise smtplib.SMTPAuthenticationError( code=-1, msg='failed get stored token') from e except OAuth2Error as e: raise smtplib.SMTPAuthenticationError(code=-1, msg=str(e)) from e try: if auth_object is None: raise smtplib.SMTPAuthenticationError( code=-1, msg='no token stored') code, resp = connection.auth( connection.auth_method, auth_object, initial_response_ok=initial_response_ok) return code, resp except smtplib.SMTPAuthenticationError as e: raise e
def test_smtp_authentication_failure(self, mock_smtp): """Check SMTP authentication failure.""" instance = mock_smtp.return_value instance.login.side_effect = smtplib.SMTPAuthenticationError( 450, "User not found") self.client.logout() username = "******" password = "******" data = {"username": username, "password": password} response = self.client.post(reverse("core:login"), data) self.assertEqual(response.status_code, 401) mock_smtp.return_value.login.assert_called_once_with( username, password) self.assertFalse( models.User.objects.filter(username=username).exists())
def test_smtp_login_error(mock_getpass, mock_SMTP_SSL, tmp_path): """Login failure.""" # Config for SSL SMTP server config_path = tmp_path/"server.conf" config_path.write_text(textwrap.dedent(u"""\ [smtp_server] host = smtp.gmail.com port = 465 security = SSL/TLS username = awdeorio """)) # Simple template sendmail_client = SendmailClient(config_path, dry_run=False) message = email.message_from_string(u"Hello world") # Mock the password entry mock_getpass.return_value = "password" # Configure SMTP login() to raise an exception mock_SMTP_SSL.return_value.__enter__.return_value.login = mock.Mock( side_effect=smtplib.SMTPAuthenticationError( code=535, msg=( "5.7.8 Username and Password not accepted. Learn more at " "5.7.8 https://support.google.com/mail/?p=BadCredentials " "xyzxyz.32 - gsmtp" ) ) ) # Send a message with pytest.raises(MailmergeError) as err: sendmail_client.sendmail( sender="*****@*****.**", recipients=["*****@*****.**"], message=message, ) # Verify exception string assert "smtp.gmail.com:465 failed to authenticate user 'awdeorio'" in\ str(err.value) assert "535" in str(err.value) assert ( "5.7.8 Username and Password not accepted. Learn more at " "5.7.8 https://support.google.com/mail/?p=BadCredentials " "xyzxyz.32 - gsmtp" ) in str(err.value)
def test_send_via_smtp_incorrect_credentials(self): smtp_settings = { 'host': 'gmail.bla.bla', 'port': 123, 'email': '*****@*****.**', 'password': '******' } to_emails = ['*****@*****.**', '*****@*****.**', '*****@*****.**'] problems = {} with patch.object(smtplib.SMTP_SSL, 'connect', return_value=(220, 'msg')) as mock_connect, \ patch.object(smtplib.SMTP_SSL, 'close', return_value=None) as mock_close: with patch.object(smtplib.SMTP_SSL, 'login') as mock_login: mock_login.side_effect = smtplib.SMTPAuthenticationError( 123, 'side effect: SMTPAuthenticationError' ) with self.assertRaises(smtplib.SMTPAuthenticationError): send_via_smtp(smtp_settings, to_emails, problems)
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_invalid_user(self, logs): """smtp.login() fails. Use a mock so we don't have failed login attempts against the real Google server. """ the_mail = Mail('*****@*****.**', 'pasword', ['*****@*****.**']) with self.assertRaisesRegex( MailException, r'Failed to send email. ' r'Check user\([email protected]\)/password is correct'): with patch.object(smtplib.SMTP, 'login', return_value=None, side_effect=smtplib.SMTPAuthenticationError( 2, 'test')): the_mail.send('hi', 'Hello!') self.assertRegex( logs.output[0], r'Failed to send email. Check user\([email protected]\)/password is correct' )
def test_shouldLogAndNotFail_whenCannotLoginToSMTP(self, get_logger_mock): # Given false_logger = Mock() get_logger_mock.return_value = false_logger false_send_mail = Mock() false_send_mail.side_effect = smtplib.SMTPAuthenticationError(534, b'5.7.14 <https://accounts.google.com/signin/continue> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 - gsmtp'); false_objects = MagicMock() false_objects.filter.return_value = [] false_users_db = MagicMock() false_users_db.objects = false_objects # When signals.send_mail_on_new_word(Translation, instance=Mock(), send=false_send_mail, user_objects=false_users_db) # Then self.assertEqual(get_logger_mock.call_args_list[0], call('learn.services.signals')) self.assertEqual(false_logger.exception.call_args_list[0], call('smtp login failed'))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://codingworld.io/project/e-mails-versenden-mit-python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from settings import settings """ Warning! If you use web.de like me, you must first allow the use of smtp and imap in the settings. Otherwise you will receive an error message: smtplib.SMTPAuthenticationError() """ def email_notification(settings, subject, text): msg = MIMEMultipart() msg['From'] = settings["senderEmail"] msg['To'] = settings["empfangsEmail"] msg['Subject'] = subject emailText = text msg.attach(MIMEText(emailText, 'html')) server = smtplib.SMTP(settings["smtp_server"],
def test_check_email_bad_credentials(self): with patch.object(EmailBackend, 'open') as connection_open: connection_open.side_effect = smtplib.SMTPAuthenticationError('550', 'Auth failed') self.assertEqual([onboarding_checks.W001], onboarding_checks.check_email_config([])) self.assertTrue(connection_open.called)
Generacion de paquetes %s iniciada el %s. Version SVN y URL para recoger paquetes: UBUNTU ==> #SVN: %s -- http://ziva.tid.indra.es/archive/ubuntu/pool/main/t/tgcm/ FEDORA ==> #SVN: %s -- http://ziva.tid.indra.es/archive/fedora16/ OpSUSE ==> #SVN: %s -- http://ziva.tid.indra.es/archive/opensuse121/ Detalle del proceso de generacion: %s Gracias por su colaboracion """ #log.debug("\tEnvio mail de aviso de paquetes disponible") asunto = mailPositivoAsunto % (resumenDistribucionesGeneradas) strInforme = "" fInf = open(ficInformeGeneracion, "r") for linea in fInf: strInforme += linea fInf.close() mensaje = mailPositivoMensaje % (distribucionesGeneradas, fechaHora, versionSVNdeb, versionSVNrpm, versionSVNrpm, strInforme) try: enviarMailConResultadoGeneracion(mailPositivoDestino, asunto, mensaje) except smtplib.SMTPAuthenticationError(code, resp): #log.error("ERROR de autenticacion ante servidor de correo!!") print "ERROR de autenticacion ante servidor de correo!!"
def sendmail(self, sender_email, recipient_email, msg): raise smtplib.SMTPAuthenticationError("code", "msg")
def send(self, recipent, filename='', subject="", message=""): # self.server.set_debuglevel(1) outer = MIMEMultipart('alternative') # outer['From'] = '<'+self.who+'>' outer['To'] = recipent outer['Subject'] = subject #outer['List-Unsubscribe'] = 'mailto:<unsubscribe@wikybetbonus>' print(outer.get('List-Unsubscribe')) msgAlternative = MIMEMultipart('alternative') msgText = MIMEText('This is the alternative plain text message.') msgAlternative.attach(msgText) outer.attach(msgAlternative) outer.attach(MIMEText(message, 'html')) print(self.who," ",recipent) for header in self.headers: outer.add_header(*header) if filename is not '': path = filename # dosyanın türünü tahmin edip ona göre type belirliyoruz ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(path) msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(path, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(path, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(path, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() """eğer yukarıdakilerden biri değilse mesajı base64 olarak encoded texte çevirip mesaja ekliyoruz""" # encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=filename) outer.attach(msg) # oluşturduğumuz text, html ve file datasını string olarak alıyoruz composed = outer.as_string() try: self.server.sendmail(self.who, [recipent], composed) Logger("Sender:{0} | Recipent:{1}, OK".format(self.who, recipent)) return True except smtplib.SMTPAuthenticationError as hata: print("e-posta veya şifrenizi yanlış girdiniz.", "orjinal hata iletisi: ", hata) raise smtplib.SMTPAuthenticationError(44, "444") except smtplib.SMTPConnectError as e: raise e except smtplib.SMTPSenderRefused as e: raise e