本文整理汇总了Python中smtplib.SMTPSenderRefused方法的典型用法代码示例。如果您正苦于以下问题:Python smtplib.SMTPSenderRefused方法的具体用法?Python smtplib.SMTPSenderRefused怎么用?Python smtplib.SMTPSenderRefused使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smtplib
的用法示例。
在下文中一共展示了smtplib.SMTPSenderRefused方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_admin_add_user_with_invalid_email
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def test_admin_add_user_with_invalid_email(self):
admin = self._create_admin()
self.client.force_login(admin)
params = dict(
username='testmail',
email='test@invalid.com',
password1='tester',
password2='tester',
)
params.update(self.add_user_inline_params)
params.update(self._additional_params_add())
with patch('allauth.account.models.EmailAddress.objects.add_email') as mocked:
mocked.side_effect = smtplib.SMTPSenderRefused(
501, '5.1.7 Bad sender address syntax', 'test_name@test_domain'
)
self.client.post(reverse(f'admin:{self.app_label}_user_add'), params)
mocked.assert_called_once()
示例2: test
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def test(self, from_addr):
try:
self.open()
self.connection.ehlo_or_helo_if_needed()
self.connection.rcpt("test@example.org")
(code, resp) = self.connection.mail(from_addr, [])
if code != 250:
logger.warning(
"Error testing mail settings, code %d, resp: %s" % (code, resp)
)
raise SMTPSenderRefused(code, resp, from_addr)
senderrs = {}
(code, resp) = self.connection.rcpt("test@example.com")
if (code != 250) and (code != 251):
logger.warning(
"Error testing mail settings, code %d, resp: %s" % (code, resp)
)
raise SMTPRecipientsRefused(senderrs)
finally:
self.close()
示例3: test_fallimento_sender
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def test_fallimento_sender(self, mock_smtp):
"""
In caso di fallimento del sender il messaggio viene rimesso in coda,
tranne che in caso di errore 5XX che è permanente
"""
codici = (451, 452, 500, 501, 421)
for codice in codici:
msg = 'code {}'.format(codice)
instance = mock_smtp.return_value
instance.sendmail.side_effect = smtplib.SMTPSenderRefused(code=codice, msg=msg, sender=Messaggio.SUPPORTO_EMAIL)
self._invia_msg_singolo()
if codice == 501:
self.assertEqual(Messaggio.in_coda().count(), 0)
else:
self.assertEqual(Messaggio.in_coda().count(), 1)
self._reset_coda()
示例4: internal_test
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def internal_test(smtp_targets, port, fromaddr, toaddr, data, subject, debug):
data += "\nThis email is part of internal relay and\\or spoofing test"
for target in smtp_targets:
LOGGER.info("[*] Checking host %s:%s for internal spoofing", target, str(port))
data += "\nVulnerable server is: %s" % target
try:
if fromaddr and toaddr: # making sure we have both from and to addresses
from_domain = fromaddr.split('@').pop() # getting the domain name from the address
to_domain = toaddr.split('@').pop() # getting the domain name from the address
if from_domain != to_domain: # making sure the spoofing is for the same domain
# otherwise it's relay and not spoofing
LOGGER.error("[!] Sender and recipient domains doesn't match!")
else:
with SMTP(target, port) as current_target:
if debug:
current_target.set_debuglevel(1)
current_target.ehlo_or_helo_if_needed()
msg = MIMEText(data)
fromaddr = fromaddr
toaddr = toaddr
msg['Subject'] = subject
msg['From'] = fromaddr
msg['To'] = toaddr
current_target.sendmail(fromaddr, toaddr, msg.as_string())
LOGGER.critical("[+] Server %s Appears to be VULNERABLE for internal "
"spoofing! Used FROM: %s", target, fromaddr)
else:
LOGGER.critical("[!] Problem with FROM and/or TO address!")
exit(1)
except (SMTPRecipientsRefused, SMTPSenderRefused) as e:
LOGGER.critical("[!] SMTP Error: %s\n[-] Server: %s NOT vulnerable or TO address "
"doesn't exist!", str(e), target)
except ConnectionRefusedError:
LOGGER.critical("[!] Connection refused by host %s", target)
except KeyboardInterrupt:
LOGGER.critical("[CTRL+C] Stopping...")
exit(1)
except Exception as e:
excptn(e)
示例5: send
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def send(self, attachment_failure=False):
"""Send the email according to the configured setup
attachment_failure - used to indicate a recursive call after the
smtp server has refused based on file size.
Should not be used externally
"""
if not self.config['shutit.core.alerting.emailer.send_mail']:
self.shutit.log('emailer.send: Not configured to send mail!',level=logging.INFO)
return True
msg = self.__compose()
mailto = [self.config['shutit.core.alerting.emailer.mailto']]
smtp = self.__get_smtp()
if self.config['shutit.core.alerting.emailer.username'] != '':
smtp.login(self.config['shutit.core.alerting.emailer.username'], self.config['shutit.core.alerting.emailer.password'])
if self.config['shutit.core.alerting.emailer.mailto_maintainer']:
mailto.append(self.config['shutit.core.alerting.emailer.maintainer'])
try:
self.shutit.log('Attempting to send email',level=logging.INFO)
smtp.sendmail(self.config['shutit.core.alerting.emailer.mailfrom'], mailto, msg.as_string())
except SMTPSenderRefused as refused:
code = refused.args[0]
if code == 552 and not attachment_failure:
self.shutit.log("Mailserver rejected message due to " + "oversize attachments, attempting to resend without",level=logging.INFO)
self.attaches = []
self.lines.append("Oversized attachments not sent")
self.send(attachment_failure=True)
else:
self.shutit.log("Unhandled SMTP error:" + str(refused),level=logging.INFO)
if not self.config['shutit.core.alerting.emailer.safe_mode']:
raise refused
except Exception as error:
self.shutit.log('Unhandled exception: ' + str(error),level=logging.INFO)
if not self.config['shutit.core.alerting.emailer.safe_mode']:
raise error
finally:
smtp.quit()
示例6: _send_batch
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def _send_batch(self, context, connection, setting):
"""
Loops through emails in a list of notifications and tries to send
to each recepient
"""
# STMP connection send loop
notifications = context['notifications']
if len(context['notifications']) == 0:
return
while True:
try:
self._send_user_notifications(context, connection)
for n in notifications:
n.is_emailed = True
n.save()
break
except smtplib.SMTPSenderRefused:
self.logger.error(
(
"E-mail refused by SMTP server ({}), "
"skipping!"
).format(setting.user.email))
continue
except smtplib.SMTPException as e:
self.logger.error(
(
"You have an error with your SMTP server "
"connection, error is: {}"
).format(e))
self.logger.error("Sleeping for 30s then retrying...")
time.sleep(30)
except Exception as e:
self.logger.error(
(
"Unhandled exception while sending, giving "
"up: {}"
).format(e))
raise
示例7: test__rest_from_mail_cmd
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def test__rest_from_mail_cmd(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
smtp.noop()
self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
self.serv._SMTPchannel.disconnect = True
with self.assertRaises(smtplib.SMTPSenderRefused):
smtp.sendmail('John', 'Sally', 'test message')
self.assertIsNone(smtp.sock)
# Issue 5713: make sure close, not rset, is called if we get a 421 error
示例8: test_421_from_mail_cmd
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def test_421_from_mail_cmd(self):
smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
smtp.noop()
self.serv._SMTPchannel.mail_response = '421 closing connection'
with self.assertRaises(smtplib.SMTPSenderRefused):
smtp.sendmail('John', 'Sally', 'test message')
self.assertIsNone(smtp.sock)
self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
示例9: sendMail
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def sendMail(message, request=None):
s = smtplib.SMTP(server)
if not testing:
try:
s.sendmail(message.sender, message.send_to, message.as_string())
except smtplib.SMTPSenderRefused as e:
if request:
request.session.flash(e[1], queue='errors')
raise
s.quit()
示例10: message_too_large
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def message_too_large(patch_token_manager, monkeypatch, request):
monkeypatch.setattr(
'inbox.sendmail.smtp.postel.SMTPConnection',
erring_smtp_connection(
smtplib.SMTPSenderRefused, 552,
request.param, None))
示例11: test_handle_disconnect
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def test_handle_disconnect(monkeypatch, smtp_port):
def simulate_disconnect(self):
raise smtplib.SMTPServerDisconnected()
monkeypatch.setattr('smtplib.SMTP.rset', simulate_disconnect)
monkeypatch.setattr('smtplib.SMTP.mail', lambda *args: (550, 'NOPE'))
conn = SMTPConnection(account_id=1,
email_address='inboxapptest@gmail.com',
smtp_username='inboxapptest@gmail.com',
auth_type='password',
auth_token='secret_password',
smtp_endpoint=('smtp.gmail.com', smtp_port),
ssl_required=True,
log=get_logger())
with pytest.raises(smtplib.SMTPSenderRefused):
conn.sendmail(['test@example.com'], 'hello there')
示例12: external_test
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def external_test(smtp_targets, port, fromaddr, recipient, data, subject, debug):
data += "\nThis email is part of external relay and\\or spoofing test"
for target in smtp_targets:
LOGGER.info("[*] Checking host " + target + ':' + str(port))
LOGGER.info("[*] Testing for mail relaying (external)")
data += "\nVulnerable server is: %s" % target
try:
if fromaddr and recipient: # checking we have both to and from addresses
with SMTP(target, port) as current_target:
if debug:
current_target.set_debuglevel(1)
current_target.ehlo_or_helo_if_needed()
################
# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = fromaddr
message["To"] = recipient
message["Subject"] = subject
# message["Bcc"] = receiver_email # Recommended for mass emails
# Add body to email
message.attach(MIMEText(data, "plain"))
# # Open PDF file in binary mode
# with open(attachment, "rb") as attached:
# # Add file as application/octet-stream
# # Email client can usually download this automatically as attachment
# part = MIMEBase("application", "octet-stream")
# part.set_payload(attached.read())
#
# # Encode file in ASCII characters to send by email
# encoders.encode_base64(part)
#
# # Add header as key/value pair to attachment part
# part.add_header(
# "Content-Disposition",
# "attachment; filename= {attachment}",
# )
#
# # Add attachment to message and convert message to string
# message.attach(part)
text = message.as_string()
##############
current_target.sendmail(fromaddr, recipient, text)
LOGGER.critical("[+] Server %s Appears to be VULNERABLE for external relay! "
"email send FROM: %s TO: %s", target, fromaddr, recipient)
else:
LOGGER.critical("[!] Problem with FROM and/or TO address!")
exit(1)
except (SMTPRecipientsRefused, SMTPSenderRefused, SMTPResponseException) as e:
LOGGER.critical("[!] SMTP Error: %s\n[-] Server: %s NOT vulnerable!", str(e), target)
except ConnectionRefusedError:
LOGGER.critical("[!] Connection refused by host %s", target)
except KeyboardInterrupt:
LOGGER.critical("[!] [CTRL+C] Stopping...")
exit(1)
except Exception as e:
excptn(e)
示例13: send_email
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def send_email(emails, subject, body):
try:
assert isinstance(emails, dict) and \
isinstance(subject, str)# and isinstance(body, str)
for key in emails:
if key == 'email':
gmail_user = emails[key]
elif key == 'psw':
gmail_pwd = emails[key]
elif key == 'to':
TO = emails[key] if type(emails[key]) is list else [emails[key]]
FROM = gmail_user
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
# If we have no internet, wait five seconds and retry
except gaierror:
try:
sleep(5)
send_email(email, subject, body)
except gaierror as e:
# If there is no internet yet, log error and move on
Logger.error(send_email, e)
except smtplib.SMTPServerDisconnected as e:
# If there is no internet yet, log error and move on
Logger.error(send_email, e)
except smtplib.SMTPSenderRefused as e:
# If there is no internet yet, log error and move on
Logger.error(send_email, e)
except Exception as e:
error_msg = '\nerror -> ' + type(e).__name__ + ' in line ' + str(
e.__traceback__.tb_lineno) + ': ' + str(e)
Logger.error(send_email, error_msg)
示例14: send_email
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def send_email(self, subject, body):
try:
assert isinstance(self.email, dict) and \
isinstance(subject, str) and isinstance(body, str)
for key in self.email:
if key == 'email':
gmail_user = self.email[key]
elif key == 'psw':
gmail_pwd = self.email[key]
elif key == 'to':
TO = self.email[key] if type(self.email[key]) is list else [self.email[key]]
FROM = gmail_user
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
# If we have no internet, wait five seconds and retry
except gaierror:
try:
sleep(5)
self.send_email(subject, body)
except gaierror as e:
# If there is no internet yet, log error and move on
Logger.error(TradingEnvironment.send_email, self.parse_error(e))
except smtplib.SMTPServerDisconnected as e:
# If there is no internet yet, log error and move on
Logger.error(TradingEnvironment.send_email, self.parse_error(e))
except smtplib.SMTPSenderRefused as e:
# If there is no internet yet, log error and move on
Logger.error(TradingEnvironment.send_email, self.parse_error(e))
except Exception as e:
try:
Logger.error(TradingEnvironment.send_email, self.parse_error(e))
if hasattr(self, 'email'):
self.send_email("Error sending email: %s at %s" % (e,
datetime.strftime(self.timestamp, "%Y-%m-%d %H:%M:%S")),
self.parse_error(e))
except Exception as e:
Logger.error(TradingEnvironment.send_email, self.parse_error(e))
示例15: deliver_testcase
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPSenderRefused [as 别名]
def deliver_testcase(self, testcase, recipient):
super().deliver_testcase(testcase, recipient)
print("Sending test case {} from test '{}' to {}".format(self.testcase_index, self.testcases.name, recipient))
self.allow_delay_increase()
try:
try:
if testcase.delivery_sender:
sender = self.sender
else:
sender = None
except AttributeError:
sender = None
try:
if testcase.delivery_recipient:
recipient = recipient
else:
recipient = None
except AttributeError:
recipient = None
result = self.smtp.send_message(testcase, sender, recipient)
if result:
for failed_recipient, (code, message) in result.items():
print("! Sending to recipient {} failed with error code {}: {}".format(failed_recipient, code, message))
self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, code, message)
if code in self.delay_increasing_status:
self.increase_delay()
else:
self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient)
except smtplib.SMTPRecipientsRefused as e:
print("! Reciepent refused")
for failed_recipient, (code, message) in e.recipients.items():
print("! Sending to recipient {} failed with error code {}: {}".format(failed_recipient, code, str(message, "iso-8859-1")))
self.logger.log(self.testcases.identifier, self.testcase_index, failed_recipient, False, code, str(message, "iso-8859-1"))
if code in self.delay_increasing_status:
self.increase_delay()
except smtplib.SMTPHeloError as e:
print("! SMTP error while HELO: " + str(e))
if e.smtp_code in self.delay_increasing_status:
self.increase_delay()
except smtplib.SMTPSenderRefused as e:
print("! SMTP server rejected sender address: " + str(e))
self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, e.smtp_code, e.smtp_error)
if e.smtp_code in self.delay_increasing_status:
self.increase_delay()
except smtplib.SMTPDataError as e:
print("! Unexpected SMTP error: " + str(e))
self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, e.smtp_code, e.smtp_error)
if e.smtp_code in self.delay_increasing_status:
self.increase_delay()
except smtplib.SMTPNotSupportedError as e:
print("! SMTP server doesn't supports: " + str(e))
self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, -1, str(e))
except smtplib.SMTPServerDisconnected as e:
self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, -2, str(e))
print("! SMTP server disconnected unexpected - reconnecting: " + str(e))
self.smtp = smtplib.SMTP(self.target)