本文整理匯總了Python中smtplib.SMTPConnectError方法的典型用法代碼示例。如果您正苦於以下問題:Python smtplib.SMTPConnectError方法的具體用法?Python smtplib.SMTPConnectError怎麽用?Python smtplib.SMTPConnectError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類smtplib
的用法示例。
在下文中一共展示了smtplib.SMTPConnectError方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: testFailingHELO
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPConnectError [as 別名]
def testFailingHELO(self):
self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
HOST, self.port, 'localhost', 3)
示例2: _send_smtp
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPConnectError [as 別名]
def _send_smtp(message, subject, to, to_name, sender, sender_name):
"""SMTP implementation of sending email."""
host = app.config.get('MAIL_HOST')
if not host:
raise MailFailure('SMTP Server Not Configured')
try:
server = smtplib.SMTP(host)
except (smtplib.SMTPConnectError, socket.error) as ex:
app.logger.error('Unable to send mail: %s', str(ex))
raise MailFailure('Error connecting to SMTP server.')
msg = text.MIMEText(message)
msg['Subject'] = subject
msg['To'] = email.utils.formataddr((to_name, to))
msg['From'] = email.utils.formataddr((sender_name, sender))
try:
if app.debug:
server.set_debuglevel(True)
server.sendmail(sender, [to], msg.as_string())
except (smtplib.SMTPException, socket.error) as ex:
app.logger.error('Unable to send mail: %s', str(ex))
raise MailFailure('Error sending mail to SMTP server.')
finally:
try:
server.quit()
except smtplib.SMTPException:
pass
示例3: send_message
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPConnectError [as 別名]
def send_message(mailfrom, rcptto, data):
try:
server = smtplib.SMTP(MX, 25, PHISH_MX)
server.sendmail(mailfrom, rcptto, data)
except smtplib.SMTPDataError as e:
print '[-] {0}'.format(str(e[1]))
except smtplib.SMTPServerDisconnected as e:
print '[-] {0}'.format(str(e))
except smtplib.SMTPConnectError as e:
print '[-] {0}'.format(str(e[1]))
示例4: test_fallimento_connect
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPConnectError [as 別名]
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()
示例5: validate_mx
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPConnectError [as 別名]
def validate_mx(server, domain):
try:
if server in MX_RECORD_CACHE:
return MX_RECORD_CACHE[server]
smtp = smtplib.SMTP(timeout=10)
smtp.connect(server)
status, _ = smtp.helo()
if status != 250:
smtp.quit()
print("%s answer: %s - %s" % (server, status, _))
smtp.mail('')
status, _ = smtp.rcpt("invalid@"+domain)
if status == 250:
smtp.quit()
MX_RECORD_CACHE[server] = True
return True
print("%s answer: %s - %s" % (server, status, _))
smtp.quit()
except smtplib.SMTPServerDisconnected as e: # Server not permits verify user
print("%s disconnected. [%s]" % (server, e))
except smtplib.SMTPConnectError as e:
print("Unable to connect to %s. [%s]" % (server, e))
except socket.timeout as e:
print("Timedout connecting to %s. [%s]" % (server, e))
MX_RECORD_CACHE[server] = False
return False
# Lookup a domain and get its mailserver
示例6: send_sms
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPConnectError [as 別名]
def send_sms(message_text, phone_number, carrier, from_address=None):
"""
Send an SMS message by emailing the carriers SMS gateway. This method
requires no money however some networks are blocked by the carriers
due to being flagged for spam which can cause issues.
:param str message_text: The message to send.
:param str phone_number: The phone number to send the SMS to.
:param str carrier: The cellular carrier that the phone number belongs to.
:param str from_address: The optional address to display in the 'from' field of the SMS.
:return: This returns the status of the sent messsage.
:rtype: bool
"""
from_address = (from_address or DEFAULT_FROM_ADDRESS)
phone_number = phone_number.replace('-', '').replace(' ', '')
# remove the country code for these 10-digit based
match = re.match('1?(?P<phone_number>[0-9]{10})', phone_number)
if match is None:
raise ValueError('the phone number appears invalid')
phone_number = match.group('phone_number')
if len(message_text) > 160:
raise ValueError('message length exceeds 160 characters')
message = MIMEText(message_text)
carrier_address = lookup_carrier_gateway(carrier)
if not carrier_address:
raise ValueError('unknown carrier specified')
to_address = "{0}@{1}".format(phone_number, carrier_address)
message['To'] = to_address
message['From'] = from_address
sms_gateways = get_smtp_servers(carrier_address)
random.shuffle(sms_gateways)
message_sent = False
for sms_gateway in sms_gateways:
try:
smtp_connection = smtplib.SMTP(sms_gateway)
smtp_connection.sendmail(from_address, [to_address], message.as_string())
smtp_connection.quit()
except (smtplib.SMTPConnectError, smtplib.SMTPDataError, smtplib.SMTPHeloError):
continue
message_sent = True
break
return message_sent
示例7: __init__
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPConnectError [as 別名]
def __init__(self,thread,starttime,opentrackurl,attach, sender , subject , message , *sendto ,**kwargs):
al = Queue()
smtp = kwargs['smtpt']
mailhost = kwargs['mailhost']
passwd = kwargs['passwd']
port = kwargs['port']
thr = int(thread)
null = ""
try:
mail = smtplib.SMTP(smtp, port)
mail.starttls()
mail.login("{}".format(mailhost), '{}'.format(passwd))
mail.quit()
for i in range(thr):
self.t = Thread(target=self.skeleton, args=(starttime,opentrackurl,attach,sender,message,subject, mailhost, passwd, smtp, int(port), al))
self.t.daemon = True
self.t.start()
for mass in sendto:
al.put(mass)
al.join()
os.startfile(os.getcwd() + '\\sleuth\\mailOpenList\\' + starttime + '.txt')
except smtplib.SMTPAuthenticationError:
print("Authentication Error", "Wrong Username or Password !", "Info")
sys.stderr.flush()
except smtplib.SMTPConnectError:
print("Connection Error", "SMTP Server Down !", "Info")
sys.stderr.flush()
except smtplib.SMTPNotSupportedError:
print("Support Error", "SMTP Not Supported !", "Info")
sys.stderr.flush()
except Exception as f:
t, o, tb = sys.exc_info()
print(f, tb.tb_lineno)
sys.stderr.flush()
#SendMail.skeleton(null,msg,mailhost,passwd,smtp,int(port),*sendto)
示例8: verify
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPConnectError [as 別名]
def verify(self, email):
"""
method that performs the verification on the passed
email address.
"""
lookup = {
'address': None,
'valid_format': False,
'deliverable': False,
'full_inbox': False,
'host_exists': False,
'catch_all': False,
}
try:
lookup['address'] = self._parse_address(email)
lookup['valid_format'] = True
except EmailFormatError:
lookup['address'] = f"{email}"
return lookup
# look for mx record and create a list of mail exchanges
try:
mx_record = resolver.query(lookup['address'].domain, 'MX')
mail_exchangers = [exchange.to_text().split() for exchange in mx_record]
lookup['host_exists'] = True
except (resolver.NoAnswer, resolver.NXDOMAIN, resolver.NoNameservers):
lookup['host_exists'] = False
return lookup
for exchange in mail_exchangers:
try:
host_exists, deliverable, catch_all = self._can_deliver(exchange, lookup['address'])
if deliverable:
lookup['host_exists'] = host_exists
lookup['deliverable'] = deliverable
lookup['catch_all'] = catch_all
break
except SMTPRecepientException as err:
# Error handlers return a dict that is then merged with 'lookup'
kwargs = handle_error.get(err.code, handle_unrecognised)(err.response)
# This expression merges the lookup dict with kwargs
lookup = {**lookup, **kwargs}
except smtplib.SMTPServerDisconnected as err:
lookup['message'] = "Internal Error"
except smtplib.SMTPConnectError as err:
lookup['message'] = "Internal Error. Maybe blacklisted"
return lookup
示例9: validate_email_address
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPConnectError [as 別名]
def validate_email_address(email_to, email_from, debug=False):
# find the appropiate mail server
domain = email_to.split('@')[1]
remote_server = get_mx_record(domain)
if (remote_server is None):
print("No valid email server could be found for [%s]!" % (email_to))
return False
# Login into the mail exchange server
try:
smtp = smtplib.SMTP()
smtp.connect(remote_server)
if debug:
smtp.set_debuglevel(True)
except smtplib.SMTPConnectError as e:
print(e)
return False
try:
smtp.ehlo_or_helo_if_needed()
except Exception as e:
print(e)
return False
# First Try to verify with VRFY
# 250 is success code. 400 or greater is error.
v_code, v_message = smtp.verify(email_to)
if v_code and v_code != 250:
f_code, f_message = smtp.mail(email_from)
# Then use RCPT to verify
if f_code and f_code == 250:
r_code, r_message = smtp.rcpt(email_to)
if r_code and r_code == 250:
return True, r_message
if r_code and r_code == 550:
return False, r_message
else:
return False
else:
return True, v_message
smtp.quit()
return False