本文整理汇总了Python中smtplib.SMTP.has_extn方法的典型用法代码示例。如果您正苦于以下问题:Python SMTP.has_extn方法的具体用法?Python SMTP.has_extn怎么用?Python SMTP.has_extn使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smtplib.SMTP
的用法示例。
在下文中一共展示了SMTP.has_extn方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
def send_email(prefs, report_str):
recipients = prefs['ADMIN_EMAIL'].split(',')
msg = dedent("""
From: %s
To: %s
Subject: %s
Date: %s
""").lstrip() % (prefs.get('SMTP_FROM'),
prefs.get('ADMIN_EMAIL'),
prefs.get('SMTP_SUBJECT'),
time.strftime(prefs.get('SMTP_DATE_FORMAT')))
msg += report_str
try:
smtp = SMTP()
if logging.getLogger().isEnabledFor(logging.DEBUG):
smtp.set_debuglevel(1)
smtp.connect(prefs.get('SMTP_HOST'),
prefs.get('SMTP_PORT'))
# If the server supports ESMTP and TLS, then convert the message exchange to TLS via the
# STARTTLS command.
if smtp.ehlo()[0] == 250:
if smtp.has_extn('starttls'):
(code, resp) = smtp.starttls()
if code != 220:
raise SMTPResponseException(code, resp)
(code, resp) = smtp.ehlo()
if code != 250:
raise SMTPResponseException(code, resp)
else:
# The server does not support esmtp.
# The Python library SMTP class handles executing HELO/EHLO commands inside
# login/sendmail methods when neither helo()/ehlo() methods have been
# previously called. Because we have already called ehlo() above, we must
# manually fallback to calling helo() here.
(code, resp) = self.helo()
if not (200 <= code <= 299):
raise SMTPHeloError(code, resp)
username = prefs.get('SMTP_USERNAME')
password = prefs.get('SMTP_PASSWORD')
if username and password:
smtp.login(username, password)
smtp.sendmail(prefs.get('SMTP_FROM'),
recipients,
msg)
debug("sent email to: %s" % prefs.get("ADMIN_EMAIL"))
except Exception, e:
print "Error sending email"
print e
print "Email message follows:"
print msg
示例2: run
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
def run(self):
# Serialize/flatten the message
fp = StringIO()
g = Generator(fp, mangle_from_=False)
g.flatten(self.msg)
contents = fp.getvalue()
for rcpt in self.rcpts:
rcpt = utils.find_address(rcpt)
smtp_server = self.MXLookup(rcpt)
conn = SMTP(smtp_server, timeout=30)
conn.set_debuglevel(True)
try:
conn.ehlo()
# FIXME: we should support an option to refuse to send messages
# if the server doesn't support STARTTLS.
if conn.has_extn('starttls'):
conn.starttls()
conn.ehlo()
# TODO: should catch exceptions here and either retry later or
# send a delivery report back to the author.
conn.sendmail(self.from_, rcpt, contents)
finally:
conn.close()
示例3: _starttls
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
def _starttls():
tlssession = SMTP()
ext_log(tlssession.connect(getconf('smtp_server'), getconf('smtp_port')), 'startTLS connection')
tlssession.ehlo()
if tlssession.has_extn('STARTTLS'):
ext_log(tlssession.starttls(context=context), 'startTLS')
tlssession.ehlo()
return tlssession
else:
logger.warning('plaintext connection')
return tlssession
示例4: debug_error_Call
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
def debug_error_Call(message):
conf = Config()
config = conf.eVerify()
logging.info("- Debug -")
smtp_server = config["SERVER"]
smtp_port = config["PORT"]
smtp_username = config["USERNAME"]
smtp_password = config["PASSWORD"]
smtp_from = config["FROM"]
smtp_to = config["D_TO"]
smtp_cc = config["D_CC"]
smtp_bcc = config["D_BCC"]
smtp_subject = config["D_SUBJECT"]
smtp_body = config["D_BODY"]
logging.info(message)
try:
logging.info("- DEBUG error is sending...")
server = SMTP(smtp_server, smtp_port)
server.set_debuglevel(True)
msg = MIMEMultipart()
msg["From"] = smtp_from
msg["To"] = "; ".join(smtp_to)
emails = [smtp_to]
if smtp_cc is not "":
msg["CC"] = "; ".join(smtp_cc)
emails += smtp_cc
if smtp_bcc is not "":
msg["BCC"] = "; ".join(smtp_bcc)
emails += smtp_bcc
msg["Subject"] = smtp_subject
body = MIMEText(message + smtp_body, "html")
msg.attach(body)
# logging.debug(msg.as_string())
# identify ourselves, prompting server for supported features
server.ehlo()
# If we can encrypt this session, do it
if server.has_extn("STARTTLS"):
server.starttls()
server.ehlo() # re-identify ourselves over TLS connection
logging.info("- DEBUG AUTOKILL sending in secure tunnel...")
server.login(smtp_username, smtp_password)
server.sendmail(smtp_from, emails, msg.as_string())
logging.info("- DEBUG ERROR MAIL sent....................................OK")
logging.info("- Error has been notified.....................................OK")
except SMTPException, sme:
logging.error("- Error notifying results by email: %s" % sme)
logging.debug("- Debug error have been NOT notified.....................FAIL")
raise OSError
示例5: EmailAlerter
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
class EmailAlerter(Alerter):
""" Sends an email alert """
required_options = frozenset(['email'])
def __init__(self, *args):
super(EmailAlerter, self).__init__(*args)
self.smtp_host = self.rule.get('smtp_host', 'localhost')
self.smtp_ssl = self.rule.get('smtp_ssl', False)
self.from_addr = self.rule.get('from_addr', 'ElastAlert')
self.smtp_port = self.rule.get('smtp_port')
if self.rule.get('smtp_auth_file'):
self.get_account(self.rule['smtp_auth_file'])
# Convert email to a list if it isn't already
if isinstance(self.rule['email'], basestring):
self.rule['email'] = [self.rule['email']]
# If there is a cc then also convert it a list if it isn't
cc = self.rule.get('cc')
if cc and isinstance(cc, basestring):
self.rule['cc'] = [self.rule['cc']]
# If there is a bcc then also convert it to a list if it isn't
bcc = self.rule.get('bcc')
if bcc and isinstance(bcc, basestring):
self.rule['bcc'] = [self.rule['bcc']]
def alert(self, matches):
body = self.create_alert_body(matches)
# Add JIRA ticket if it exists
if self.pipeline is not None and 'jira_ticket' in self.pipeline:
url = '%s/browse/%s' % (self.pipeline['jira_server'], self.pipeline['jira_ticket'])
body += '\nJIRA ticket: %s' % (url)
to_addr = self.rule['email']
email_msg = MIMEText(body.encode('UTF-8'), _charset='UTF-8')
email_msg['Subject'] = self.create_title(matches)
email_msg['To'] = ', '.join(self.rule['email'])
email_msg['From'] = self.from_addr
email_msg['Reply-To'] = self.rule.get('email_reply_to', email_msg['To'])
email_msg['Date'] = formatdate()
if self.rule.get('cc'):
email_msg['CC'] = ','.join(self.rule['cc'])
to_addr = to_addr + self.rule['cc']
if self.rule.get('bcc'):
to_addr = to_addr + self.rule['bcc']
try:
if self.smtp_ssl:
if self.smtp_port:
self.smtp = SMTP_SSL(self.smtp_host, self.smtp_port)
else:
self.smtp = SMTP_SSL(self.smtp_host)
else:
if self.smtp_port:
self.smtp = SMTP(self.smtp_host, self.smtp_port)
else:
self.smtp = SMTP(self.smtp_host)
self.smtp.ehlo()
if self.smtp.has_extn('STARTTLS'):
self.smtp.starttls()
if 'smtp_auth_file' in self.rule:
self.smtp.login(self.user, self.password)
except (SMTPException, error) as e:
raise EAException("Error connecting to SMTP host: %s" % (e))
except SMTPAuthenticationError as e:
raise EAException("SMTP username/password rejected: %s" % (e))
self.smtp.sendmail(self.from_addr, to_addr, email_msg.as_string())
self.smtp.close()
elastalert_logger.info("Sent email to %s" % (self.rule['email']))
def create_default_title(self, matches):
subject = 'ElastAlert: %s' % (self.rule['name'])
# If the rule has a query_key, add that value plus timestamp to subject
if 'query_key' in self.rule:
qk = matches[0].get(self.rule['query_key'])
if qk:
subject += ' - %s' % (qk)
return subject
def get_info(self):
return {'type': 'email',
'recipients': self.rule['email']}
示例6: notify
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
def notify(state):
logging.debug("EmailNotifier is notifying...")
smtp_server = EmailNotifiers.config['smtp_server']
smtp_port = EmailNotifiers.config['smtp_port']
smtp_username = EmailNotifiers.config['smtp_username']
smtp_password = EmailNotifiers.config['smtp_password']
smtp_from = EmailNotifiers.config['smtp_from']
smtp_to = EmailNotifiers.config['smtp_to']
smtp_cc = None
if 'smtp_cc' in EmailNotifiers.config.keys():
smtp_cc = EmailNotifiers.config['smtp_cc']
smtp_bcc = None
if 'smtp_bcc' in EmailNotifiers.config.keys():
smtp_bcc = EmailNotifiers.config['smtp_bcc']
smtp_subject = EmailNotifiers.config['smtp_subject']
smtp_body = EmailNotifiers.config['smtp_body']
smtp_body = smtp_body.replace('XXX', '<p>' + state + '</p>')
try:
server = SMTP(smtp_server, smtp_port)
server.set_debuglevel(False)
msg = MIMEMultipart()
msg['From'] = smtp_from
msg['To'] = '; '.join(smtp_to)
emails = [smtp_to]
if smtp_cc is not None:
msg['CC'] = '; '.join(smtp_cc)
emails += smtp_cc
if smtp_bcc is not None:
msg['BCC'] = '; '.join(smtp_bcc)
emails += smtp_bcc
msg['Subject'] = smtp_subject
body = MIMEText(smtp_body, 'html')
msg.attach(body)
logging.debug(msg.as_string())
try:
file = os.path.join(EmailNotifiers.config['dir_out'], EmailNotifiers.config['serial_file'])
logging.debug("attaching file: '%s'" % (file))
fp = open(file, 'rb')
part = MIMEApplication(fp.read(), 'text/plain', filename=EmailNotifiers.config['serial_file'])
part.add_header('Content-Disposition', 'attachment', filename=EmailNotifiers.config['serial_file'])
msg.attach(part)
fp.close()
except OSError, e:
logging.error("Error attaching file '%s': %s" % (file, e))
raise OSError
# identify ourselves, prompting server for supported features
server.ehlo()
# If we can encrypt this session, do it
if server.has_extn('STARTTLS'):
server.starttls()
server.ehlo() # re-identify ourselves over TLS connection
server.login(smtp_username, smtp_password)
server.sendmail(smtp_from[0], emails, msg.as_string())
logging.debug('Email sent...')
示例7: EmailAlerter
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
class EmailAlerter(Alerter):
""" Sends an email alert """
required_options = frozenset(["email"])
def __init__(self, *args):
super(EmailAlerter, self).__init__(*args)
self.smtp_host = self.rule.get("smtp_host", "localhost")
self.smtp_ssl = self.rule.get("smtp_ssl", False)
self.from_addr = self.rule.get("from_addr", "ElastAlert")
self.smtp_port = self.rule.get("smtp_port")
if self.rule.get("smtp_auth_file"):
self.get_account(self.rule["smtp_auth_file"])
# Convert email to a list if it isn't already
if isinstance(self.rule["email"], str):
self.rule["email"] = [self.rule["email"]]
# If there is a cc then also convert it a list if it isn't
cc = self.rule.get("cc")
if cc and isinstance(cc, str):
self.rule["cc"] = [self.rule["cc"]]
# If there is a bcc then also convert it to a list if it isn't
bcc = self.rule.get("bcc")
if bcc and isinstance(bcc, str):
self.rule["bcc"] = [self.rule["bcc"]]
def alert(self, matches):
body = ""
for match in matches:
body += unicode(BasicMatchString(self.rule, match))
# Separate text of aggregated alerts with dashes
if len(matches) > 1:
body += "\n----------------------------------------\n"
# Add JIRA ticket if it exists
if self.pipeline is not None and "jira_ticket" in self.pipeline:
url = "%s/browse/%s" % (self.pipeline["jira_server"], self.pipeline["jira_ticket"])
body += "\nJIRA ticket: %s" % (url)
to_addr = self.rule["email"]
email_msg = MIMEText(body.encode("UTF-8"), _charset="UTF-8")
email_msg["Subject"] = self.create_title(matches)
email_msg["To"] = ", ".join(self.rule["email"])
email_msg["From"] = self.from_addr
email_msg["Reply-To"] = self.rule.get("email_reply_to", email_msg["To"])
if self.rule.get("cc"):
email_msg["CC"] = ",".join(self.rule["cc"])
to_addr = to_addr + self.rule["cc"]
if self.rule.get("bcc"):
to_addr = to_addr + self.rule["bcc"]
try:
if self.smtp_ssl:
if self.smtp_port:
self.smtp = SMTP_SSL(self.smtp_host, self.smtp_port)
else:
self.smtp = SMTP_SSL(self.smtp_host)
else:
if self.smtp_port:
self.smtp = SMTP(self.smtp_host, self.smtp_port)
else:
self.smtp = SMTP(self.smtp_host)
self.smtp.ehlo()
if self.smtp.has_extn("STARTTLS"):
self.smtp.starttls()
if "smtp_auth_file" in self.rule:
self.smtp.login(self.user, self.password)
except (SMTPException, error) as e:
raise EAException("Error connecting to SMTP host: %s" % (e))
except SMTPAuthenticationError as e:
raise EAException("SMTP username/password rejected: %s" % (e))
self.smtp.sendmail(self.from_addr, to_addr, email_msg.as_string())
self.smtp.close()
elastalert_logger.info("Sent email to %s" % (self.rule["email"]))
def create_default_title(self, matches):
subject = "ElastAlert: %s" % (self.rule["name"])
# If the rule has a query_key, add that value plus timestamp to subject
if "query_key" in self.rule:
qk = matches[0].get(self.rule["query_key"])
if qk:
subject += " - %s" % (qk)
return subject
def get_info(self):
return {"type": "email", "recipients": self.rule["email"]}
示例8: EmailConnection
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
class EmailConnection(object):
def __init__(self, server, username, password, debug=False):
if ':' in server:
data = server.split(':')
self.server = data[0]
self.port = int(data[1])
else:
self.server = server
self.port = 25
self.username = username
self.password = password
self.connect(debug)
def __enter__(self):
return self
def __exit__(self, exception_type, exception_val, trace):
self.close()
def connect(self, debug):
self.connection = SMTP(host=self.server, port=self.port)
if debug: # Debug Information
# self.debuglevel = 1
self.connection.set_debuglevel(debug)
# identify ourselves, prompting server for supported features
self.connection.ehlo()
# If we can encrypt this session, do it
if self.connection.has_extn('STARTTLS'):
self.connection.starttls()
self.connection.ehlo()
self.connection.esmtp_features['auth'] = 'PLAIN LOGIN'
self.connection.login(self.username, self.password)
def send(self, message, from_=None, to=None, verify=False):
if type(message) == str:
if from_ is None or to is None:
raise EmailConnectionError('You need to specify `from_` '
'and `to`')
else:
from_ = get_email(from_)
to = get_email(to)
else:
from_ = message.email['From']
if 'Cc' not in message.email:
message.email['Cc'] = ''
if 'bcc' not in message.email:
message.email['bcc'] = ''
to_emails = list(message.email['To'].split(',')) + \
message.email['Cc'].split(',') + \
message.email['bcc'].split(',')
to = [get_email(complete_email) for complete_email in to_emails]
message = str(message)
if verify:
for each_email in to_emails:
self.connection.verify(each_email)
# TODO option - remove emails that failed verification
# return self.connection.sendmail(from_, to, message)
try:
self.connection.sendmail(from_, to, message)
except SMTPException:
raise SendEmailError('Message Could not be sent!')
def close(self):
self.connection.close()
示例9: notify
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
def notify():
print("EmailNotifier is notifying the results...")
smtp_server = EmailNotifiers.config['smtp_server']
smtp_port = EmailNotifiers.config['smtp_port']
smtp_username = EmailNotifiers.config['smtp_username']
smtp_password = EmailNotifiers.config['smtp_password']
smtp_from = EmailNotifiers.config['smtp_from']
smtp_to = EmailNotifiers.config['smtp_to']
smtp_cc = None
if 'smtp_cc' in EmailNotifiers.config.keys():
smtp_cc = EmailNotifiers.config['smtp_cc']
smtp_bcc = None
if 'smtp_bcc' in EmailNotifiers.config.keys():
smtp_bcc = EmailNotifiers.config['smtp_bcc']
smtp_subject = EmailNotifiers.config['smtp_subject']
smtp_body = EmailNotifiers.config['smtp_body']
try:
server = SMTP(smtp_server, smtp_port)
#server.set_debuglevel(True)
msg = MIMEMultipart()
msg['From'] = smtp_from
msg['To'] = ';'.join(smtp_to)
emails = [smtp_to]
if smtp_cc is not None:
msg['CC'] = ';'.join(smtp_cc)
emails += smtp_cc
if smtp_bcc is not None:
msg['BCC'] = ';'.join(smtp_bcc)
emails += smtp_bcc
msg['Subject'] = smtp_subject
body = MIMEText(smtp_body, 'html')
msg.attach(body)
print(msg.as_string())
try:
def all_files_under(path):
for cur_path, dirnames, filenames in os.walk(path):
for filename in filenames:
if '.txt' in filename:
yield os.path.join(cur_path, filename)
for file in all_files_under('./out'):
print("attaching file: '%s'" % (file))
fp = open(file, 'rb')
part = MIMEApplication(fp.read(), 'text/plain', filename=file.split('/')[2])
part.add_header('Content-Disposition', 'attachment', filename=file.split('/')[2])
msg.attach(part)
fp.close()
except OSError, e:
logging.error("Error walking dir '%s': %s" % (dir, e))
raise OSError
# identify ourselves, prompting server for supported features
server.ehlo()
# If we can encrypt this session, do it
if server.has_extn('STARTTLS'):
server.starttls()
server.ehlo() # re-identify ourselves over TLS connection
server.login(smtp_username, smtp_password)
server.sendmail(smtp_from[0], emails, msg.as_string())
print('Email sent...')
示例10: interceptCall
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
def interceptCall(f):
now = datetime.datetime.now()
now_month = now.month
# data format: YYYYMMDD
if int(now_month) < 10:
now_month = "0" + str(now.month)
today = str(now.year) + str(now_month) + str(now.day)
conf = Config()
config = conf.eVerify()
logging.info("- INTERCEPT STARTED -")
smtp_server = config["SERVER"]
smtp_port = config["PORT"]
smtp_username = config["USERNAME"]
smtp_password = config["PASSWORD"]
smtp_from = config["FROM"]
smtp_to = config["E_TO"]
smtp_cc = config["E_CC"]
smtp_bcc = config["E_BCC"]
smtp_subject = config["E_SUBJECT"]
smtp_body = config["E_BODY"]
file_name = config["E_ATTACHMENT"] + str(today) + ".txt"
file_attach = f
try:
logging.info("- INTERCEPT is sending...")
server = SMTP(smtp_server, smtp_port)
server.set_debuglevel(True)
msg = MIMEMultipart()
msg["From"] = smtp_from
msg["To"] = "; ".join(smtp_to)
emails = [smtp_to]
if smtp_cc is not "":
msg["CC"] = "; ".join(smtp_cc)
emails += smtp_cc
if smtp_bcc is not "":
msg["BCC"] = "; ".join(smtp_bcc)
emails += smtp_bcc
msg["Subject"] = smtp_subject
body = MIMEText(smtp_body, "html")
msg.attach(body)
try:
logging.info("- Attaching file: {0}".format(str(file_attach)))
with open(file_attach, "rb") as fil:
part = MIMEApplication(fil.read(), "text/plain", filename=file_name)
part.add_header("Content-Disposition", "attachment", filename=file_name)
msg.attach(part)
except OSError, e:
logging.error("- Error walking dir '%s': %s" % (dir, e))
raise OSError
# identify ourselves, prompting server for supported features
server.ehlo()
# If we can encrypt this session, do it
if server.has_extn("STARTTLS"):
server.starttls()
server.ehlo() # re-identify ourselves over TLS connection
logging.info("- INTERCEPT CALL sending in secure tunnel...")
server.login(smtp_username, smtp_password)
server.sendmail(smtp_from, emails, msg.as_string())
logging.info("- INTERCEPT email sent........................................OK")
logging.info("- Results have been notified..................................OK")
示例11: notify
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
def notify():
print("EmailNotifier is notifying the results...")
smtp_server = EmailNotifiers.config["smtp_server"]
smtp_port = EmailNotifiers.config["smtp_port"]
smtp_username = EmailNotifiers.config["smtp_username"]
smtp_password = EmailNotifiers.config["smtp_password"]
smtp_from = EmailNotifiers.config["smtp_from"]
smtp_to = EmailNotifiers.config["smtp_to"]
smtp_cc = None
if "smtp_cc" in EmailNotifiers.config.keys():
smtp_cc = EmailNotifiers.config["smtp_cc"]
smtp_bcc = None
if "smtp_bcc" in EmailNotifiers.config.keys():
smtp_bcc = EmailNotifiers.config["smtp_bcc"]
smtp_subject = EmailNotifiers.config["smtp_subject"]
smtp_body = EmailNotifiers.config["smtp_body"]
try:
server = SMTP(smtp_server, smtp_port)
# server.set_debuglevel(True)
msg = MIMEMultipart()
msg["From"] = smtp_from
msg["To"] = ";".join(smtp_to)
emails = [smtp_to]
if smtp_cc is not None:
msg["CC"] = ";".join(smtp_cc)
emails += smtp_cc
if smtp_bcc is not None:
msg["BCC"] = ";".join(smtp_bcc)
emails += smtp_bcc
msg["Subject"] = smtp_subject
body = MIMEText(smtp_body, "html")
msg.attach(body)
print(msg.as_string())
try:
def all_files_under(path):
for cur_path, dirnames, filenames in os.walk(path):
for filename in filenames:
if ".html" in filename:
yield os.path.join(cur_path, filename)
for file in all_files_under("./out"):
print("attaching file: '%s'" % (file))
fp = open(file, "rb")
part = MIMEApplication(fp.read(), "text/plain", filename=file.split("/")[2])
part.add_header("Content-Disposition", "attachment", filename=file.split("/")[2])
msg.attach(part)
fp.close()
except OSError, e:
logging.error("Error walking dir '%s': %s" % (dir, e))
raise OSError
# identify ourselves, prompting server for supported features
server.ehlo()
# If we can encrypt this session, do it
if server.has_extn("STARTTLS"):
server.starttls()
server.ehlo() # re-identify ourselves over TLS connection
server.login(smtp_username, smtp_password)
server.sendmail(smtp_from[0], emails, msg.as_string())
print("Email sent...")
示例12: notify
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import has_extn [as 别名]
def notify():
logging.debug("EmailNotifier is notifying typosquatted websites...")
smtp_server = EmailNotifiers.config['smtp_server']
smtp_port = EmailNotifiers.config['smtp_port']
smtp_username = EmailNotifiers.config['smtp_username']
smtp_password = EmailNotifiers.config['smtp_password']
smtp_from = EmailNotifiers.config['smtp_from']
smtp_to = EmailNotifiers.config['smtp_to']
smtp_cc = None
if 'smtp_cc' in EmailNotifiers.config.keys():
smtp_cc = EmailNotifiers.config['smtp_cc']
smtp_bcc = None
if 'smtp_bcc' in EmailNotifiers.config.keys():
smtp_bcc = EmailNotifiers.config['smtp_bcc']
smtp_subject = EmailNotifiers.config['smtp_subject']
smtp_body = EmailNotifiers.config['smtp_body']
try:
server = SMTP(smtp_server, smtp_port)
#server.set_debuglevel(True)
msg = MIMEMultipart()
msg['From'] = smtp_from
msg['To'] = ';'.join(smtp_to)
emails = [smtp_to]
if smtp_cc is not None:
msg['CC'] = ';'.join(smtp_cc)
emails += smtp_cc
if smtp_bcc is not None:
msg['BCC'] = ';'.join(smtp_bcc)
emails += smtp_bcc
msg['Subject'] = smtp_subject
body = MIMEText(smtp_body, 'html')
msg.attach(body)
logging.debug(msg.as_string())
try:
latest_file = max(Utility.all_files_under(EmailNotifiers.config['dir_out']), key=os.path.getmtime)
if latest_file is not '':
logging.debug("attaching file: '%s'" % (latest_file))
fp = open(latest_file, 'rb')
part = MIMEApplication(fp.read(), 'text/plain', filename=latest_file.split('/')[1])
part.add_header('Content-Disposition', 'attachment', filename=latest_file.split('/')[1])
msg.attach(part)
fp.close()
except OSError, e:
logging.error("Error walking dir '%s': %s" % (dir, e))
raise OSError
# identify ourselves, prompting server for supported features
server.ehlo()
# If we can encrypt this session, do it
if server.has_extn('STARTTLS'):
server.starttls()
server.ehlo() # re-identify ourselves over TLS connection
server.login(smtp_username, smtp_password)
server.sendmail(smtp_from, emails, msg.as_string())
logging.debug('Email sent...')