Skip to content

Instantly share code, notes, and snippets.

@yudai09
Created June 28, 2017 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yudai09/b2f28db98dc32598aba4442e62775f09 to your computer and use it in GitHub Desktop.
Save yudai09/b2f28db98dc32598aba4442e62775f09 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import email
import poplib
import time
import smtplib
import sys
import traceback
# ------目的---------------------
# このスクリプトはメール配送にかかっている時間を測定する。
# Zabbix等と組み合わせてメールの遅延状況を監視するために使うことを想定している。
#
# ------動作---------------------
# このスクリプトは特定のメールアドレスにメールを1通送る。
# そして同時に当該のメールアドレスに送信されたメールをすべて受信する。
# 次に受信したメール1通ずつに対し、Receivedヘッダを解析し、
# そのメールがボックスに配送されるまでに要した時間(遅延時間)を解析する。
# 最後に、すべてのメールの遅延時間の最大を標準出力に書き込む。
#
# ------Zabbixとの組み合わせ------
# Zabbixはzabbix-agentが動作するサーバ上のシェルを呼び出すことができる。
# それを利用し、このスクリプトを呼び出し、標準出力に書き込まれた
# 最大遅延時間を監視することでメールの遅延状況を監視できる。
conf_smtp = {
'server' : 'your smtp submission server',
'fromaddr' : 'email sender',
'toaddr' : 'email recepient',
'subject': 'subject here',
'user' : 'smtp auth account',
'password' : 'smtp auth password',
}
conf_pop = {
'server' : 'your POP server',
'port' : 995,
# user shoud be same with toaddr in `conf_smtp`
'user' : 'pop account',
'password' : 'pop passoword',
}
def send_email(debug=False):
conf = conf_smtp
# connect and send mail
server = smtplib.SMTP(conf['server'])
server.login(conf['user'], conf['password'])
if debug:
server.set_debuglevel(1)
msg = ('From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n'
% (conf['fromaddr'], conf['toaddr'], conf['subject']))
server.sendmail(conf['fromaddr'], conf['toaddr'], msg)
server.quit()
# get delay of emails by comaparing dates in `Received` headers.
def get_max_delay_in_mailbox(debug=False):
conf = conf_pop
# connect POP server and receive mails
conn = poplib.POP3_SSL(conf['server'], conf['port'])
conn.user(conf['user'])
conn.pass_(conf['password'])
num_messages = len(conn.list()[1])
if num_messages == 0:
if debug:
print 'no email found.'
return 0
delays = []
for i in range(num_messages):
msg = '\n'.join(conn.retr(i+1)[1])
mail = email.message_from_string(msg)
received_dates = []
if debug:
print 'Subject: %s, Date %s' % (mail['Subject'], mail['Date'])
for received_hdr in mail.get_all('Received'):
# last part of 'Received:' header separated by ';' shoud be a date.
date = received_hdr.split(';')[-1]
date = email.utils.parsedate_tz(date)
date = email.utils.mktime_tz(date)
received_dates.append(date)
received_dates = sorted(received_dates)
delay = received_dates[-1] - received_dates[0]
if debug:
print 'delay %s %s' % (delay, received_dates)
delays.append(delay)
# delete read mail
conn.dele(i+1)
# close POP connection
conn.quit()
return sorted(delays)[-1]
def main(debug=False):
try:
send_email(debug)
print(get_max_delay_in_mailbox(debug))
except Exception as e:
# some thing happen
print 'error: %s' % (e)
print traceback.format_exc()
sys.exit(1)
sys.exit(0)
if __name__ == '__main__':
debug = False
if len(sys.argv) == 2:
if sys.argv[1] == 'debug':
print 'debug mode'
debug = True
main(debug)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment