GetEmailAlerts/get.py

63 lines
1.8 KiB
Python
Raw Permalink Normal View History

2023-05-15 07:27:24 -04:00
import imaplib
import email
2023-05-16 21:44:11 -04:00
from email.header import decode_header
2023-05-15 07:27:24 -04:00
from getpass import getpass
2023-05-16 21:44:11 -04:00
import json
2023-05-15 07:27:24 -04:00
# IMAP server settings for Hotmail
imap_server = 'imap-mail.outlook.com'
imap_port = 993
# Email credentials
email_address = input('Email address: ')
password = getpass('Password: ')
# Connect to the IMAP server
imap_conn = imaplib.IMAP4_SSL(imap_server, imap_port)
# Login to the email account
imap_conn.login(email_address, password)
# Select the 'alerts' folder
imap_conn.select('Alerts')
2023-05-15 07:59:27 -04:00
# Search for unseen emails in the 'alerts' folder, starting with the newest
status, response = imap_conn.uid('search', None, 'UNSEEN')
email_ids = response[0].split()
# Loop through the email UIDs
for email_id in email_ids:
# Fetch the email by UID
status, response = imap_conn.uid('fetch', email_id, '(RFC822)')
raw_email = response[0][1]
2023-05-15 07:27:24 -04:00
email_message = email.message_from_bytes(raw_email)
2023-05-16 21:44:11 -04:00
# Extract the sender and receipt date of the email
email_from = str(decode_header(email_message['From'])[0][0])
email_date = email_message['Date']
2023-05-15 07:27:24 -04:00
# Extract the body of the email
if email_message.is_multipart():
for part in email_message.get_payload():
if part.get_content_type() == 'text/plain':
email_body = part.get_payload(decode=True).decode()
break
else:
email_body = email_message.get_payload(decode=True).decode()
2023-05-16 21:44:11 -04:00
# Create a dictionary with the email details
email_details = {
'id': email_id.decode(),
'from': email_from,
'date': email_date,
'body': email_body
}
# Print the JSON representation of the email details
print(json.dumps(email_details, indent=4))
2023-05-15 07:27:24 -04:00
# Logout and close the connection
imap_conn.logout()
imap_conn.close()
2023-05-16 21:44:11 -04:00