Reading email from command line:
Using openssl https://tewarid.github.io/2011/05/10/access-imap-server-from-the-command-line-using-openssl.html
openssl s_client -connect sneakymailer.htb:993 -crlf
tag login username password
tag LIST "" "*"
tag select INBOX
Using telnet:
telnet sneakymailer.htb 143
TODO - clean-up email saving / attachment downloading¶
python:
import imaplib
import email
host = "sneakymailer.htb"
username = "username"
password = "password"
imap = imaplib.IMAP4_SSL(host)
imap.login(username, password)
save_and_open_in_browser = False
def main():
folders = [folder.decode().split('"."')[1].strip() for folder in imap.list()[1]]
for folder in folders:
status, messages = imap.select(folder)
messages = int(messages[0])
print(f"folder: {folder}")
print(f"# of messages: {messages}\n")
if messages > 0:
print("="*100)
for num in range(messages):
get_email(num+1)
def get_email(num):
res, msg = imap.fetch(str(num), "(RFC822)")
for response in msg:
if isinstance(response, tuple):
# parse a bytes email into a message object
msg = email.message_from_bytes(response[1])
# decode the email subject
subject = decode_header(msg["Subject"])[0][0]
if isinstance(subject, bytes):
# if it's a bytes, decode to str
subject = subject.decode()
# email sender
from_ = msg.get("From")
print("Subject:", subject)
print("From:", from_)
# if the email message is multipart
if msg.is_multipart():
# iterate over email parts
for part in msg.walk():
# extract content type of email
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
try:
# get the email body
body = part.get_payload(decode=True).decode()
except:
pass
if content_type == "text/plain" and "attachment" not in content_disposition:
# print text/plain emails and skip attachments
print(body)
elif "attachment" in content_disposition:
# download attachment
filename = part.get_filename()
if filename:
if not os.path.isdir(subject):
# make a folder for this email (named after the subject)
os.mkdir(subject)
filepath = os.path.join(subject, filename)
# download attachment and save it
open(filepath, "wb").write(part.get_payload(decode=True))
else:
# extract content type of email
content_type = msg.get_content_type()
# get the email body
body = msg.get_payload(decode=True).decode()
if content_type == "text/plain":
# print only text email parts
print(body)
if content_type == "text/html" and save_and_open_in_browser:
# if it's HTML, create a new HTML file and open it in browser
if not os.path.isdir(subject):
# make a folder for this email (named after the subject)
os.mkdir(subject)
filename = f"{subject[:50]}.html"
filepath = os.path.join(subject, filename)
# write the file
open(filepath, "w").write(body)
# open in the default browser
webbrowser.open(filepath)
print("="*100)