Simple Python library for reading verification emails via IMAP — OTP extraction, link parsing, auto IMAP detection.
Project description
imap_reader
Simple, clean Python library for reading verification emails via IMAP — with OTP extraction, verification link parsing, and auto IMAP detection.
Zero external dependencies — uses Python standard library only (imaplib, email, re, threading).
Installation
pip install git+https://github.com/nabilunnuha/imap_reader.git
Quick Start
from imap_reader import LoginEmail
with LoginEmail(
email_address="user@gmail.com",
password_email="your_app_password",
) as client:
for msg in client.get_messages("UNSEEN"):
print(msg.subject)
print(msg.otp_codes) # ['123456']
print(msg.verification_links) # ['https://example.com/verify?token=...']
Features
- IMAP auto-detect — otomatis mendeteksi IMAP host dari domain email
- OTP extraction — ekstrak kode 4–8 digit dari isi email
- Verification link extraction — temukan dan prioritaskan link verifikasi/konfirmasi
- HTML email parser — konversi HTML email ke plain text untuk ekstraksi
- Login timeout — raise error jika koneksi melebihi batas waktu (30–60 detik)
- Context manager — gunakan
withstatement untuk auto-close koneksi - Delete messages — hapus email berdasarkan kriteria (
ALL,SEEN,UNSEEN) - Type hints — fully typed, friendly untuk IDE dan autocomplete
Usage
Basic — Baca email UNSEEN
from imap_reader import LoginEmail
with LoginEmail("user@gmail.com", "app_password") as client:
for msg in client.get_messages("UNSEEN"):
print(f"From : {msg.sender}")
print(f"Subject : {msg.subject}")
print(f"OTP : {msg.otp_codes}")
print(f"Links : {msg.verification_links}")
Ambil hanya 1 email terbaru
with LoginEmail("user@gmail.com", "app_password") as client:
msg = client.get_latest_message("UNSEEN")
if msg:
print(msg.otp_codes)
Custom timeout (30–60 detik direkomendasikan)
with LoginEmail(
email_address="user@gmail.com",
password_email="app_password",
timeout=60, # detik
) as client:
msg = client.get_latest_message()
Baca dari folder tertentu
with LoginEmail("user@gmail.com", "app_password") as client:
for msg in client.get_messages("ALL", folder="SPAM"):
print(msg.subject)
Hapus email
with LoginEmail("user@gmail.com", "app_password") as client:
# Hapus semua email yang sudah dibaca
count = client.delete_messages("SEEN")
print(f"{count} email dihapus")
# Hapus semua email di INBOX
count = client.delete_messages("ALL", folder="INBOX")
# Hapus email belum dibaca di SPAM
count = client.delete_messages("UNSEEN", folder="SPAM")
Tambah custom IMAP provider
from imap_reader import LoginEmail
from imap_reader.models import DEFAULT_IMAP_LIST, ImapItemModel
DEFAULT_IMAP_LIST.append(
ImapItemModel(domain="mycompany.com", imap_host="imap.mycompany.com")
)
with LoginEmail("user@mycompany.com", "password") as client:
for msg in client.get_messages():
print(msg)
Error handling
from imap_reader import LoginEmail
from imap_reader.exceptions import (
AuthenticationError,
ConnectionTimeoutError,
ImapNotFoundError,
)
try:
with LoginEmail("user@gmail.com", "wrong_password", use_default_imap=False, timeout=10) as client:
msg = client.get_latest_message()
except AuthenticationError:
print("Email atau password salah.")
except ConnectionTimeoutError:
print("Koneksi ke server IMAP timeout.")
except ImapNotFoundError:
print("Domain email tidak dikenali, tambahkan manual ke imap_list.")
API Reference
LoginEmail(email_address, password_email, imap_list=None, timeout=30)
| Parameter | Type | Default | Deskripsi |
|---|---|---|---|
email_address |
str |
— | Alamat email lengkap |
password_email |
str |
— | Password IMAP atau App Password |
imap_list |
list |
DEFAULT_IMAP_LIST |
List IMAP provider |
use_default_imap |
bool |
True |
Password IMAP atau App Password |
timeout |
int |
30 |
Batas waktu login dalam detik |
Methods
| Method | Return | Deskripsi |
|---|---|---|
get_messages(criteria, folder, limit, mark_seen) |
Generator[EmailMessage] |
Fetch dan yield pesan |
get_latest_message(criteria, folder) |
EmailMessage | None |
Ambil 1 pesan terbaru |
delete_messages(criteria, folder) |
int |
Hapus pesan, return jumlah yang dihapus |
close() |
None |
Tutup koneksi IMAP |
criteria → Literal["ALL", "SEEN", "UNSEEN"]
folder → Literal["INBOX", "SENT", "DRAFTS", "TRASH", "SPAM", "JUNK"]
EmailMessage attributes
| Attribute | Type | Deskripsi |
|---|---|---|
uid |
str |
IMAP UID pesan |
subject |
str |
Subject email (decoded) |
sender |
str |
Pengirim / From header (decoded) |
date |
str |
Tanggal email |
body_text |
str |
Body plain text |
body_html |
str |
Body HTML mentah |
otp_codes |
list[str] |
Kode OTP yang ditemukan |
verification_links |
list[str] |
URL verifikasi (prioritas pertama) |
Exceptions
| Exception | Kapan terjadi |
|---|---|
LoginEmailError |
Base exception |
AuthenticationError |
Kredensial salah |
ConnectionTimeoutError |
Login melebihi batas timeout |
ImapNotFoundError |
Domain email tidak dikenali |
Supported Email Providers (auto-detect)
| Provider | Domain |
|---|---|
| Gmail | gmail.com, googlemail.com |
| Yahoo Mail | yahoo.com, yahoo.co.id |
| Outlook / Hotmail / Live | outlook.com, hotmail.com, live.com |
| iCloud / Me / Mac | icloud.com, me.com, mac.com |
| ProtonMail | protonmail.com, proton.me |
| Zoho Mail | zoho.com |
| AOL Mail | aol.com |
| Mail.com | mail.com |
| Yandex | yandex.com, yandex.ru |
| GMX | gmx.com, gmx.net |
Provider lain bisa ditambahkan manual via
ImapItemModel.
Gmail Setup
Gmail memerlukan App Password, bukan password biasa.
- Buka Google Account → Security
- Aktifkan 2-Step Verification
- Buka App Passwords → Generate password baru
- Gunakan password tersebut sebagai
password_email
Project Structure
imap_reader/
├── __init__.py # Public API
├── client.py # Core IMAP client & LoginEmail class
├── models.py # ImapItemModel, EmailMessage, DEFAULT_IMAP_LIST
├── parser.py # OTP, link, HTML extraction utilities
└── exceptions.py # Custom exceptions
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file imap_reader-1.0.1.tar.gz.
File metadata
- Download URL: imap_reader-1.0.1.tar.gz
- Upload date:
- Size: 12.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cbf5827aaded59888d490718339cfd744a6ff9823eadf489d8b29475c9cd3f4a
|
|
| MD5 |
138240e88be8495aa1143dcee1ec046d
|
|
| BLAKE2b-256 |
3621fa729dc31456d02cd0e5c36e369aa833739396d1d034fd029bb685cb16c9
|
File details
Details for the file imap_reader-1.0.1-py3-none-any.whl.
File metadata
- Download URL: imap_reader-1.0.1-py3-none-any.whl
- Upload date:
- Size: 11.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
65a45b17c9f2a8d58ed7755817f55cbe4ec8a61640ad558eb2dcf9739c89f17f
|
|
| MD5 |
bbfe6e40c4836590f875b403e8b5b9a1
|
|
| BLAKE2b-256 |
c0a958cd2994141345b3679c6cb93051f4e1199bdbb41807ec49f231596e9844
|