import imaplib
import email
from email.header import decode_header
# Configuration information
IMAP_SERVER = "mailx.serv00.com " # mailx.serv00.com x represents the number of your server
EMAIL = "[email protected]" # your email address
PASSWORD = "your-password" # your email password
try:
# Connect to the IMAP server
print(f"Connecting to {IMAP_SERVER}...")
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
# Login
print("Logging in...")
mail.login(EMAIL, PASSWORD)
print("Login successful!")
# Select the inbox
mail.select("inbox")
print("Inbox selected.")
# Search for emails (e.g., all emails)
status, messages = mail.search(None, "ALL")
if status != "OK":
print("No emails found.")
exit()
# Get the list of email IDs
email_ids = messages[0].split()
print(f"Found {len(email_ids)} emails.")
# Iterate through each email
for i, email_id in enumerate(email_ids[-5:], start=1): # Only read the last 5 emails
print(f"\nReading email {i}...")
# Get the email content
status, msg_data = mail.fetch(email_id, "(RFC822)")
if status != "OK":
print("Unable to read email content.")
continue
# Parse the email content
for response_part in msg_data:
if isinstance(response_part, tuple):
msg = email.message_from_bytes(response_part[1]) # Parse the email
# Extract the email subject
subject, encoding = decode_header(msg["Subject"])[0]
if isinstance(subject, bytes):
subject = subject.decode(encoding or "utf-8")
print(f"Subject: {subject}")
# Extract the sender
from_ = msg.get("From")
print(f"From: {from_}")
# Extract the email body
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
# Extract plain text content
if content_type == "text/plain" and "attachment" not in content_disposition:
body = part.get_payload(decode=True).decode()
print(f"Body:\n{body}")
else:
body = msg.get_payload(decode=True).decode()
print(f"Body:\n{body}")
except imaplib.IMAP4.error as e:
print(f"IMAP error: {e}")
except Exception as e:
print(f"Other error: {e}")
finally:
# Close the connection
if 'mail' in locals():
mail.logout()
print("Disconnected.")
## Code Analysis
(1) Connect and log in
Use imaplib.IMAP4_SSL to connect to the IMAP server.
Call the login method for authentication.
(2) Select the email folder
Use select("inbox") to select the inbox. You can also select other folders, such as "Sent" or "Drafts".
(3) Search for emails
Use search(None, "ALL") to find all emails.
The returned messages are a byte string list containing email IDs.
(4) Get the email content
Use fetch(email_id, "(RFC822)") to get the full content of the specified email.
RFC822 indicates that the complete email data is returned.
(5) Parse the email content
Use email.message_from_bytes to parse the email data into a MIME object.
Use decode_header to decode the email subject and sender information.
If the email is multipart, iterate through each part to extract the body or attachments.
## Handling Attachments
If the email contains attachments, you can extract them by checking the Content-Disposition. Here is the code snippet for handling attachments:
# Code Analysis
## 1. Connect and log in
- Use `imaplib.IMAP4_SSL` to connect to the IMAP server.
- Call the `login` method for authentication.
## 2. Select the email folder
- Use `select("inbox")` to select the inbox. You can also select other folders, such as "Sent" or "Drafts".
## 3. Search for emails
- Use `search(None, "ALL")` to find all emails.
- The returned `messages` is a byte string list containing email IDs.
## 4. Get the email content
- Use `fetch(email_id, "(RFC822)")` to get the full content of the specified email.
- `RFC822` indicates that the complete email data is returned.
## 5. Parse the email content
- Use `email.message_from_bytes` to parse the email data into a MIME object.
- Use `decode_header` to decode the email subject and sender information.
- If the email is multipart, iterate through each part to extract the body or attachments.
## 6. Handling Attachments
If the email contains attachments, you can extract them by checking `Content-Disposition`. Here is the code snippet for handling attachments:
```python
if "attachment" in content_disposition:
filename = part.get_filename()
if filename:
filepath = f"./attachments/{filename}"
with open(filepath, "wb") as f:
f.write(part.get_payload(decode=True))
print(f"Attachment saved: {filepath}")