Created
February 1, 2018 15:05
-
-
Save Baekalfen/e592f13ce38e7357b3a43ebd69c21ad5 to your computer and use it in GitHub Desktop.
Check if two mail servers are alive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import smtplib | |
import imaplib | |
import time | |
import random | |
import string | |
def send_mail(smtp_server, SSL, username, password, receiver, subject, body): | |
to = [receiver] | |
email_text = """\ | |
From: %s | |
To: %s | |
Subject: %s | |
%s | |
""" % (username, ", ".join(to), subject, body) | |
server = None | |
if SSL: | |
server = smtplib.SMTP_SSL(smtp_server, 465) | |
else: | |
server = smtplib.SMTP(smtp_server, 587) | |
server.starttls() | |
server.ehlo() | |
server.login(username, password) | |
server.sendmail(username, to, email_text) | |
server.close() | |
return True | |
def check_mail(imap_server, username, password, search_query): | |
M = imaplib.IMAP4_SSL(imap_server) | |
M.login(username, password) | |
found = False | |
for n in range(60): | |
M.select() | |
typ, data = M.search(None, 'ALL') | |
for num in data[0].split(): | |
typ, data = M.fetch(num, '(RFC822)') | |
if search_query in data[0][1]: | |
found = True | |
break | |
if found: | |
break | |
time.sleep(5) | |
M.close() | |
M.logout() | |
return found | |
def get_random_string(N=64): | |
return ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(N)) | |
gmail_user = 'REDACTED' | |
gmail_pass = 'REDACTED' | |
server = 'REDACTED' | |
user = 'REDACTED' | |
password = "REDACTED" | |
random_body = get_random_string() | |
print "Random body:", random_body | |
print "Sending from Gmail" | |
assert send_mail('smtp.gmail.com', True, gmail_user, gmail_pass, user, 'subject', random_body) | |
print "Check if mail was received" | |
assert check_mail(server, user, password, random_body) | |
random_body = get_random_string() | |
print "Random body:", random_body | |
print "Sending to Gmail" | |
assert send_mail(server, False, user, password, gmail_user, 'subject', random_body) | |
print "Check if mail was received" | |
assert check_mail("imap.gmail.com", gmail_user, gmail_pass, random_body) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment