Check email với Python

Check email với Python

Trong Python, chúng ta có thể check email sử dụng thư viện tích hợp

smtplib

IMAP

Để gửi một email, chúng ta có thể sử dụng thư viện

smtplib

Sau đây là một ví dụ đơn giản

import smtplib

sender_email = ‘your_email@domain.com’
receiver_email = ‘receiver_email@domain.com’
password = ‘your_email_password’

message = “””\
Subject: Hi there

This is a test email sent from Python.”””

try:
server = smtplib.SMTP(‘smtp.gmail.com’, 587)
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
print(‘Email sent’)
except Exception as e:
print(e)
finally:
server.quit()

Để check các emails, chúng ta có thể sử dụng thư viện

IMAP

Sau đây là một ví dụ đơn giản

import imaplib
import email

username = ‘your_email@domain.com’
password = ‘your_email_password’
imap_url = ‘imap.gmail.com’

# create an IMAP4 class with SSL
imap = imaplib.IMAP4_SSL(imap_url)

# login to our email account
imap.login(username, password)

# select the inbox
imap.select(‘inbox’)

# search for emails with a specific subject line
status, response = imap.search(None, ‘SUBJECT “Subject line”‘)

# split the response string into individual email IDs
msg_ids = response[0].split()

# loop through the message IDs
for msg_id in msg_ids:
# fetch the email message by ID
status, msg = imap.fetch(msg_id, ‘(RFC822)’)
# parse the email message into an email object
email_msg = email.message_from_bytes(msg[0][1])
# print the email subject line
print(email_msg[‘Subject’])

# logout of the email account
imap.logout()

Hiệu lực hóa các địa chỉ email

Có các cách thức khác nhau để hiệu lực hóa một địa chỉ email trong Python, nhưng một cách là sử dụng regular expressions.
Sau đây là một ví dụ về một hàm cái sử dụng các regular expressions để hiệu lực hóa một địa chỉ email:

python
import re

def is_valid_email(email):
pattern = r’^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$’
if re.match(pattern, email):
return True
else:
return False

Trong hàm này, mô hình regular expression

r’^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$’

 

khớp một string cái bắt đầu với một hay nhiều hơn một các kí tự anphabe số, dấu chấm, dấu gạch dưới, dấu %, dấu cộng
hay dấu gạch ngang theo sau bởi kí hiệu @, theo sau bởi một hay nhiều hơn một các kí tự anphabe số, dấu chấm, hay
dấu gạch ngang theo sau bởi một “.”, theo sau bởi hai hay nhiều hơn hai các kí tự anphabe số
Hàm

re.match(pattern, email)

check xem nếu email khớp mô hình, và nếu nó khớp, trả về true. Mặt khác, nó trả về false. Chú ý rằng hàm này không
đảm bảo rằng địa chỉ email là có hiệu lực hay đã tồn tại, nhưng nó có thể giúp lọc ra các địa chỉ email không có hiệu
lực rõ ràng.

Chia sẻ