def logout(self): """Logout""" if self.debug: self._login = False self._needstls = True self.server = None self.logger.debug('Logout successful (DEBUG MODE)') return if not self._login: self.logger.warning('{} Logout before login!'.format( self.__repr__())) return try: code, message = self.server.docmd("QUIT") if code != 221: raise smtplib.SMTPResponseException(code, message) except smtplib.SMTPServerDisconnected: pass finally: self.server.close() self.server = None self._login = False self.logger.debug('Logout successful')
def _deliver(self, envelope): refused = {} try: if self._use_ssl: s = smtplib.SMTP_SSL() else: s = smtplib.SMTP() s.connect(self._host, self._port) if self._starttls: s.starttls() s.ehlo() if self._auth_user and self._auth_password: s.login(self._auth_user, self._auth_password) try: refused = s.sendmail(envelope.mail_from, envelope.rcpt_tos, envelope.original_content) finally: s.quit() except (OSError, smtplib.SMTPException) as e: logging.exception('got %s', e.__class__) # All recipients were refused. If the exception had an associated # error code, use it. Otherwise, fake it with a SMTP 554 status code. errcode = getattr(e, 'smtp_code', 554) errmsg = getattr(e, 'smtp_error', e.__class__) raise smtplib.SMTPResponseException(errcode, errmsg.decode())
async def __exit__(self, *args): try: code, message = await self.docmd("QUIT") if code != 221: raise smtplib.SMTPResponseException(code, message) except smtplib.SMTPServerDisconnected: pass finally: self.close()
def test_remote_response_error(mock_send, error, mailer, message, caplog): mock_send.side_effect = smtplib.SMTPResponseException(error[0], error[1]) mailer.send(message) assert len(caplog.record_tuples) == 1 _, severity, msg = caplog.record_tuples[0] assert severity == logging.ERROR assert f'Error while sending message: {error[0]} - {error[1].decode()}' in msg
def authenticate(self, url, consumer, token): if consumer is not None and not isinstance(consumer, oauth.Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, oauth.Token): raise ValueError("Invalid token.") xoauth_string = oauth.build_xoauth_string(url, consumer, token) code, resp = self.docmd('AUTH', 'XOAUTH %s' % base64.b64encode(xoauth_string)) if code >= 500: raise smtplib.SMTPResponseException(code, resp) return code, resp
async def getreply(self): """Get a reply from the server. Returns a tuple consisting of: - server response code (e.g. '250', or such, if all goes well) Note: returns -1 if it can't read response code. - server response string corresponding to response code (multiline responses are converted to a single, multiline string). Raises SMTPServerDisconnected if end-of-file is reached. """ resp = [] if self.file is None: self.file = self.sock.makefile('rb') while 1: try: line = await self.file.readline() except OSError as e: self.close() raise smtplib.SMTPServerDisconnected( "Connection unexpectedly closed: " + str(e)) if not line: self.close() raise smtplib.SMTPServerDisconnected( "Connection unexpectedly closed") if self.debuglevel > 0: self._print_debug('reply:', repr(line)) if len(line) > MAXLINE: self.close() raise smtplib.SMTPResponseException(500, "Line too long.") resp.append(line[4:].strip(b' \t\r\n')) code = line[:3] # Check that the error code is syntactically correct. # Don't attempt to read a continuation line if it is broken. try: errcode = int(code) except ValueError: errcode = -1 break # Check if multiline response. if line[3:4] != b"-": break errmsg = b"\n".join(resp) if self.debuglevel > 0: self._print_debug('reply: retcode (%s); Msg: %a' % (errcode, errmsg)) return errcode, errmsg
def test_send_mail_error_420(mocker): # We monkeypatch smtplib.SMTP class mocksmtpcls = mocker.patch("smtplib.SMTP") # sendmail raises SMTPResponseException mocksmtpcls.return_value.sendmail.side_effect = smtplib.SMTPResponseException( 420, "Timeout connection problem") # We check that send_email will raise SMTP exception 420 with pytest.raises(smtplib.SMTPResponseException, match=r".*420.*Timeout.*") as e: # noqa: E501 send_email("*****@*****.**", "*****@*****.**", "coucou", "comment ça va ?\nbisous") # noqa: E501 mocksmtpcls.return_value.sendmail.assert_called_once()
def _deliver(self, envelope): refused = {} try: s = smtplib.SMTP_SSL('smtp.gmail.com') s.connect('smtp.gmail.com', 465) s.login(self.login, self.password) try: refused = s.sendmail(envelope.mail_from, envelope.rcpt_tos, envelope.original_content) finally: s.quit() except (OSError, smtplib.SMTPException) as e: errcode = getattr(e, 'smtp_code', 554) errmsg = getattr(e, 'smtp_error', e.__class__) raise smtplib.SMTPResponseException(errcode, errmsg.decode())
def configure_host(self): if self.mail.use_ssl: host = smtplib.SMTP_SSL(self.mail.server, self.mail.port) else: host = smtplib.SMTP(self.mail.server, self.mail.port) host.set_debuglevel(int(self.mail.debug)) if self.mail.use_tls: (resp, reply) = host.starttls() # Fix CVE-2016-0772 on old Python installations if resp != 200: raise smtplib.SMTPResponseException(resp, reply) if self.mail.username and self.mail.password: host.login(self.mail.username, self.mail.password) return host
def _deliver(self, envelope): refused = {} try: s = smtplib.SMTP(host='127.0.0.1', port=1025) refused = s.sendmail(envelope.mail_from, envelope.rcpt_tos, envelope.original_content) s.quit() except (OSError, smtplib.SMTPException) as e: print(">> SMTP Relay to MailHog failed") try: print("> Relay to SES/SMTP Create...") s = smtplib.SMTP(host=self._host, port=self._port, local_hostname=self._local_hostname) s.set_debuglevel(self._debug_level) print("> Created") #s.connect(self._host, self._port) if self._starttls: print("> Started TLS") #s.starttls() s.ehlo(self._local_hostname) s.starttls() print("> EHLO Done") if self._auth_user and self._auth_password: print("> Login Started") s.login(self._auth_user, self._auth_password) print("> Login Done") try: print("> Sending...") refused = s.sendmail(envelope.mail_from, envelope.rcpt_tos, envelope.original_content) print("> Sending Done") finally: print("> Quit...") s.quit() print("> Quit OK") except (OSError, smtplib.SMTPException) as e: logging.exception('got %s', e.__class__) # All recipients were refused. If the exception had an associated # error code, use it. Otherwise, fake it with a SMTP 554 status code. errcode = getattr(e, 'smtp_code', 554) errmsg = getattr(e, 'smtp_error', e.__class__) raise smtplib.SMTPResponseException(errcode, errmsg.decode())
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_notify_failed_2(self): settings = EmailSettings() with self.assertRaises(EmailException) as e: self.notifier.notify('hello', 'yay') self.assertEqual(1, e.exception.code) self.assertEqual('Settings not specified', e.exception.message) self.notifier.update_settings(settings) with self.assertRaises(EmailException) as e: self.notifier.notify('hello', 'yay') self.assertEqual(2, e.exception.code) self.assertEqual('SMTP host not specified', e.exception.message) settings.host = self.helper.real_host self.notifier.update_settings(settings) with self.assertRaises(EmailException) as e: self.notifier.notify('hello', 'yay') self.assertEqual(3, e.exception.code) self.assertEqual('Email to address not specified', e.exception.message) settings.host = self.helper.real_host settings.port = self.helper.real_port settings.to_addr = self.helper.real_to_addr settings.login = self.helper.real_login settings.password = self.helper.real_password settings.connection_security = str( self.helper.real_connection_security) self.notifier.update_settings(settings) server = Mock() self.notifier._create_server = Mock(return_value=server) self.notifier._server_authenticate = Mock(return_value=server) server.sendmail = Mock( side_effect=smtplib.SMTPResponseException(3, "132")) with self.assertRaises(EmailException) as e: self.notifier.notify('hello', 'yay') self.assertEqual(5, e.exception.code) self.assertEqual('SMTP: failed to deliver the message', e.exception.message)
def logout(self): if not self._login: self.log_exception('{} Logout before login!'.format(self.__repr__())) return if self.debug: self.log_access('logout') # Copied from smtplib.SMTP.__exit__ # used for close connection. try: code, message = self.server.docmd("QUIT") if code != 221: raise smtplib.SMTPResponseException(code, message) except smtplib.SMTPServerDisconnected: pass finally: self.server.close() self._remove_server() self._login = False
def __init__(self, hostname, username=None, password=None, ssl=True, port=None, ssl_context=None, starttls=False): self.server = SmtpTransport(hostname, port=port, ssl=ssl, ssl_context=ssl_context, starttls=starttls) self.username = username self.password = password try: self.connection = self.server.connect(username, password) except smtplib.SMTPResponseException as e: raise smtplib.SMTPResponseException(e.smtp_code, e.smtp_error)
def logout(self): """Logout""" if self.debug: self._login = False self.server = None self.print('Logout successful (DEBUG MODE)') return if not self._login: self.print('Logout before login!') return try: code, message = self.server.docmd("QUIT") if code != 221: raise smtplib.SMTPResponseException(code, message) except smtplib.SMTPServerDisconnected: pass finally: self.server.close() self.server = None self._login = False self.print('Logout successful')
def test_mail_mail_send_exceptions_raise_management(self): """ Test various use case with exceptions and errors and see how they are managed and stored at mail and notification level. """ mail, notification = self.test_mail, self.test_notification mail.write({ 'email_from': '*****@*****.**', 'email_to': '*****@*****.**' }) # SMTP connecting issues with self.mock_mail_gateway(): _connect_current = self.connect_mocked.side_effect # classic errors that may be raised during sending, just to test their current support for error, msg in [ (smtplib.SMTPServerDisconnected('SMTPServerDisconnected'), 'SMTPServerDisconnected'), (smtplib.SMTPResponseException('code', 'SMTPResponseException'), 'code\nSMTPResponseException'), (smtplib.SMTPNotSupportedError('SMTPNotSupportedError'), 'SMTPNotSupportedError'), (smtplib.SMTPException('SMTPException'), 'SMTPException'), (SSLError('SSLError'), 'SSLError'), (gaierror('gaierror'), 'gaierror'), (timeout('timeout'), 'timeout') ]: def _connect(*args, **kwargs): raise error self.connect_mocked.side_effect = _connect mail.send(raise_exception=False) self.assertFalse(mail.failure_type) self.assertEqual(mail.failure_reason, msg) self.assertEqual(mail.state, 'exception') self.assertEqual(notification.failure_type, 'mail_smtp') self.assertEqual(notification.notification_status, 'exception') self._reset_data() self.connect_mocked.side_effect = _connect_current # SMTP sending issues with self.mock_mail_gateway(): _send_current = self.send_email_mocked.side_effect self._reset_data() mail.write({'email_to': '*****@*****.**'}) # should always raise for those errors, even with raise_exception=False for error, error_class in [ (smtplib.SMTPServerDisconnected("Some exception"), smtplib.SMTPServerDisconnected), (MemoryError("Some exception"), MemoryError) ]: def _send_email(*args, **kwargs): raise error self.send_email_mocked.side_effect = _send_email with self.assertRaises(error_class): mail.send(raise_exception=False) self.assertFalse( mail.failure_reason, 'SMTPServerDisconnected/MemoryError during Send raises and lead to a rollback' ) self.assertFalse( mail.failure_type, 'SMTPServerDisconnected/MemoryError during Send raises and lead to a rollback' ) self.assertEqual( mail.state, 'outgoing', 'SMTPServerDisconnected/MemoryError during Send raises and lead to a rollback' ) self.assertFalse( notification.failure_type, 'SMTPServerDisconnected/MemoryError during Send raises and lead to a rollback' ) self.assertEqual( notification.notification_status, 'ready', 'SMTPServerDisconnected/MemoryError during Send raises and lead to a rollback' ) # MailDeliveryException: should be catched; other issues are sub-catched under # a MailDeliveryException and are catched for error, msg in [ (MailDeliveryException("Some exception"), 'Some exception'), (ValueError("Unexpected issue"), 'Unexpected issue') ]: def _send_email(*args, **kwargs): raise error self.send_email_mocked.side_effect = _send_email self._reset_data() mail.send(raise_exception=False) self.assertEqual(mail.failure_reason, msg) self.assertFalse(mail.failure_type, 'Mail: unlogged failure type to fix') self.assertEqual(mail.state, 'exception') self.assertEqual(notification.failure_type, 'unknown', 'Mail: generic failure type') self.assertEqual(notification.notification_status, 'exception') self.send_email_mocked.side_effect = _send_current
def send(self, fromaddr, toaddrs, message): raise smtplib.SMTPResponseException(self.code, 'Serious Error')
def send_mail(self, sender, receivers, mail_subject, mail_content, cc=None, bcc=None, attachment_names=None, illustrate_names=None): receivers = str(receivers).split(',') attachment_name_list = [] if attachment_names != None: attachment_name_list = str(attachment_names).split(',') illustrate_name_list = [] if illustrate_names != None: illustrate_name_list = str(illustrate_names).split(',') if len(attachment_name_list) == 0 and len(illustrate_name_list) == 0: message = MIMEText(mail_content, 'html', 'utf-8') message['From'] = sender message['To'] = ','.join(receivers) message['Subject'] = mail_subject if cc != None: cc = str(cc).split(',') receivers.extend(cc) message['Cc'] = ','.join(cc) if bcc != None: bcc = str(bcc).split(',') receivers.extend(bcc) message['Bcc'] = ','.join(bcc) try: self.connection.sendmail(sender, receivers, message.as_string()) return True except smtplib.SMTPException: return False if len(attachment_name_list) != 0 and len(illustrate_name_list) == 0: # 创建一个带附件的实例 message = MIMEMultipart() message['From'] = sender message['To'] = ','.join(receivers) message['Subject'] = mail_subject if cc != None: cc = str(cc).split(',') receivers.extend(cc) message['Cc'] = ','.join(cc) if bcc != None: bcc = str(bcc).split(',') receivers.extend(bcc) message['Bcc'] = ','.join(bcc) # 邮件正文内容 message.attach(MIMEText(mail_content, 'html', 'utf-8')) # 构造附件 for attach_name in attachment_name_list: if self.is_contain_chinese(attach_name): attach = MIMEText( open(attachment_path + "/" + attach_name, 'rb').read(), 'base64', 'utf-8') attach["Content-Type"] = 'application/octet-stream' attach.add_header("Content-Disposition", "attachment", filename=("gbk", "", attach_name)) message.attach(attach) else: attach = MIMEText( open(attachment_path + "/" + attach_name, 'rb').read(), 'base64', 'utf-8') attach["Content-Type"] = 'application/octet-stream' attach[ "Content-Disposition"] = 'attachment; filename="' + attach_name + '"' message.attach(attach) try: self.connection.sendmail(sender, receivers, message.as_string()) for attach_name in attachment_name_list: my_file = attachment_path + "/" + attach_name if os.path.exists(my_file): os.remove(my_file) return True except smtplib.SMTPException: return False if len(attachment_name_list) == 0 and len(illustrate_name_list) != 0: # 创建一个带插图的实例 msg_root = MIMEMultipart('related') msg_root['From'] = sender msg_root['To'] = ','.join(receivers) msg_root['Subject'] = mail_subject if cc != None: cc = str(cc).split(',') receivers.extend(cc) msg_root['Cc'] = ','.join(cc) if bcc != None: bcc = str(bcc).split(',') receivers.extend(bcc) msg_root['Bcc'] = ','.join(bcc) # 邮件正文内容 msg_alternative = MIMEMultipart('alternative') msg_alternative.attach(MIMEText(mail_content, 'html', 'utf-8')) msg_root.attach(msg_alternative) # 构造插图 for illustrate_name in illustrate_name_list: if not self.is_contain_chinese(illustrate_name): fp = open(illustrate_path + "/" + illustrate_name, 'rb') msg_image = MIMEImage(fp.read()) fp.close() msg_image.add_header('Content-ID', '<' + illustrate_name + '>') msg_root.attach(msg_image) else: raise smtplib.SMTPResponseException( 1, "Illustration's name can not be chinese!") try: self.connection.sendmail(sender, receivers, msg_root.as_string()) for illustrate_name in illustrate_name_list: my_file = illustrate_path + "/" + illustrate_name if os.path.exists(my_file): os.remove(my_file) return True except smtplib.SMTPException: return False if len(attachment_name_list) != 0 and len(illustrate_name_list) != 0: # 创建一个带附件的实例 msg_root = MIMEMultipart('related') # msg_root['From'] = formataddr([sender, sender], charset='utf-8') # msg_root['To'] = formataddr([receiver, receiver], charset='utf-8') msg_root['From'] = sender msg_root['To'] = ','.join(receivers) msg_root['Subject'] = mail_subject if cc != None: cc = str(cc).split(',') receivers.extend(cc) msg_root['Cc'] = ','.join(cc) if bcc != None: bcc = str(bcc).split(',') receivers.extend(bcc) msg_root['Bcc'] = ','.join(bcc) # 邮件正文内容 msg_alternative = MIMEMultipart('alternative') msg_alternative.attach(MIMEText(mail_content, 'html', 'utf-8')) msg_root.attach(msg_alternative) # 构造附件 for attach_name in attachment_name_list: if self.is_contain_chinese(attach_name): attach = MIMEText( open(attachment_path + "/" + attach_name, 'rb').read(), 'base64', 'utf-8') attach["Content-Type"] = 'application/octet-stream' attach.add_header("Content-Disposition", "attachment", filename=("gbk", "", attach_name)) msg_root.attach(attach) else: attach = MIMEText( open(attachment_path + "/" + attach_name, 'rb').read(), 'base64', 'utf-8') attach["Content-Type"] = 'application/octet-stream' attach[ "Content-Disposition"] = 'attachment; filename="' + attach_name + '"' msg_root.attach(attach) # 构造插图 for illustrate_name in illustrate_name_list: if not self.is_contain_chinese(illustrate_name): fp = open(illustrate_path + "/" + illustrate_name, 'rb') msg_image = MIMEImage(fp.read()) fp.close() msg_image.add_header('Content-ID', '<' + illustrate_name + '>') msg_root.attach(msg_image) else: raise smtplib.SMTPResponseException( 1, "Illustration's name can not be chinese!") try: self.connection.sendmail(sender, receivers, msg_root.as_string()) for attach_name in attachment_name_list: my_file = attachment_path + "/" + attach_name if os.path.exists(my_file): os.remove(my_file) for illustrate_name in illustrate_name_list: my_file = illustrate_path + "/" + illustrate_name if os.path.exists(my_file): os.remove(my_file) return True except smtplib.SMTPException: return False return False