Làm cách nào để đọc email bằng IMAP trong Python?

imaplib là gói cài đặt IMAP, một giao thức email tiêu chuẩn lưu trữ email trên máy chủ thư, nhưng cho phép người dùng cuối xem và thao tác với thư như thể chúng được lưu trữ cục bộ trên (các) thiết bị máy tính của người dùng cuối

base64 là gói cung cấp mã hóa hoặc giải mã dữ liệu nhị phân thành ký tự ASCII hoặc ngược lại

email_user = input('Email: ')
email_pass = input('Password: ')
0 là một gói sử dụng mà chúng tôi có thể thao tác các thư mục tệp có trên máy tính để bàn cục bộ của chúng tôi

email_user = input('Email: ')
email_pass = input('Password: ')
1 là gói dùng để đọc, viết và gửi email từ tập lệnh python của bạn

Trước tiên, chúng tôi cần email_id và mật khẩu để truy cập email

email_user = input('Email: ')
email_pass = input('Password: ')

Bạn, nhập email và mật khẩu để truy cập email

mail = imaplib.IMAP4_SSL(“host”,port)

Bây giờ, chúng tôi đã tạo kết nối với máy chủ qua ổ cắm được mã hóa SSL. Cổng tiêu chuẩn cho IMAP4_SSL là 993. Nếu tài khoản của bạn là Gmail thì địa chỉ máy chủ là “imap. gmail. com”

mail.login(email_user, email_pass)

Bây giờ, chúng tôi đã đăng nhập vào thư của bạn và chúng tôi có toàn quyền truy cập vào tất cả các email

mail.select()

Điều này chọn thư mục hoặc nhãn bạn muốn đọc thư từ. Nếu bạn viết

email_user = input('Email: ')
email_pass = input('Password: ')
2 thì chúng tôi đã chọn thư mục hộp thư đến

type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()

email_user = input('Email: ')
email_pass = input('Password: ')
3 tìm kiếm từ thư ở đây bạn có thể cung cấp các bộ lọc như từ, đến hoặc chủ đề của thư được tìm thấy.
email_user = input('Email: ')
email_pass = input('Password: ')
4 là bộ ký tự và
email_user = input('Email: ')
email_pass = input('Password: ')
5 trả về tất cả thư mà không cần bất kỳ bộ lọc nào. Hàm này trả về 2 giá trị một là
email_user = input('Email: ')
email_pass = input('Password: ')
6 đó là liệu yêu cầu có phải là
email_user = input('Email: ')
email_pass = input('Password: ')
7 hay không. Nếu
email_user = input('Email: ')
email_pass = input('Password: ')
7 điều đó có nghĩa là yêu cầu đã thành công. Trong khi
email_user = input('Email: ')
email_pass = input('Password: ')
9 là id của tất cả các email

for num in data[0].split():
typ, data = mail.fetch(num, '(RFC822)' )
raw_email = data[0][1]
# converts byte literal to string removing b''
raw_email_string = raw_email.decode('utf-8')
email_message = email.message_from_string(raw_email_string)
# downloading attachments
for part in email_message.walk():
# this part comes from the snipped I don't understand yet..
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = part.get_filename()
if bool(fileName):
filePath = os.path.join('/Users/sanketdoshi/python/', fileName)
if not os.path.isfile(filePath) :
fp = open(filePath, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
subject = str(email_message).split("Subject: ", 1)[1].split("\nTo:", 1)[0]
print('Downloaded "{file}" from email titled "{subject}" with UID {uid}.'.format(file=fileName, subject=subject, uid=latest_email_uid.decode('utf-8')))

Bây giờ, chúng tôi đang lặp lại từ tất cả các id và sẽ in từ chủ đề, nội dung thư

mail = imaplib.IMAP4_SSL(“host”,port)
0 tìm nạp thư cho id đã cho trong đó
mail = imaplib.IMAP4_SSL(“host”,port)
1 là Giao thức truy cập thư trên Internet. Bây giờ, bạn có thể sử dụng
mail = imaplib.IMAP4_SSL(“host”,port)
2 để lấy tiêu đề thư.
email_user = input('Email: ')
email_pass = input('Password: ')
9 từ tìm nạp được mã hóa nhị phân nên chúng tôi cần giải mã theo bộ ký tự UTF-8. Bây giờ, hãy chuyển chuỗi đã giải mã đó tới
mail = imaplib.IMAP4_SSL(“host”,port)
4 để chấp nhận một chuỗi và chuyển đổi nó thành định dạng từ điển với các trường bắt buộc.
mail = imaplib.IMAP4_SSL(“host”,port)
5 được sử dụng để lặp qua cây thư.
mail = imaplib.IMAP4_SSL(“host”,port)
6 là nhiều phần nếu email chứa tệp đính kèm hoặc nếu không thì đó là văn bản/đơn giản

Python 3 có các thư viện tích hợp cho IMAP, POP3 và SMTP. Chúng ta sẽ tập trung tìm hiểu cách gửi thư bằng SMTP và đọc/quản lý email bằng IMAP. Chúng tôi cũng sẽ xem xét cách gửi tin nhắn văn bản SMS bằng email

Nếu bạn cần dịch vụ lưu trữ email của riêng mình, hãy xem Interserver. lưu trữ mạng nơi bạn có thể lưu trữ email không giới hạn cho các miền không giới hạn với giá rẻ chỉ $4/tháng. Bạn cũng có thể thiết lập máy chủ SMTP của riêng mình trên VPS, nhưng điều đó thật rắc rối

Một lưu ý về Gmail

Gmail sẽ không cho phép bạn sử dụng IMAP hoặc POP theo mặc định và bạn phải bật tính năng này

Để thực hiện việc này, hãy đi tới cài đặt Gmail của bạn và chọn "Bật IMAP" trong tab "Chuyển tiếp và POP/IMAP". Nhìn thấy. Kiểm tra Gmail thông qua các nền tảng email khác để biết thêm thông tin

Tên người dùng của bạn là địa chỉ email đầy đủ tại Gmail. Cả IMAP và SMTP đều yêu cầu xác thực. Tên máy chủ và cổng là

  • hình ảnh. gmail. com. 993 (đã bật SSL/TLS)
  • smtp. gmail. com. 465 (đã bật SSL/TLS) Cổng 587 cho TLS/STARTTLS

Đọc email với IMAP

Để tìm nạp email, bạn có thể sử dụng poplib cho POP3 hoặc imaplib cho IMAP4. Chúng tôi sẽ chỉ tập trung vào IMAP cung cấp cho bạn nhiều tùy chọn hơn

Sử dụng hoặc phân loại tùy thuộc vào việc bạn có đang sử dụng SSL hay không. Ví dụ này sẽ sử dụng

import imaplib
# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host='mail.example.com')
imap_server.login('[email protected]', '$ecret')
imap_server.select()  # Default is `INBOX`

# Find all emails in inbox and print out the raw email data
_, message_numbers_raw = imap_server.search(None, 'ALL')
for message_number in message_numbers_raw[0].split():
    _, msg = imap_server.fetch(message_number, '(RFC822)')
    print(msg[0][1])
1

  • Cổng 143 - Cổng IMAP không được mã hóa mặc định
  • Cổng 993 - Cổng SSL IMAP mặc định
imaplib.IMAP4(host='', port=IMAP4_PORT)

imaplib.IMAP4_SSL(host='', port=IMAP4_SSL_PORT, keyfile=None, certfile=None, ssl_context=None)

Để giữ cho ví dụ đầu tiên đơn giản, đây là một ví dụ đơn giản tối thiểu về việc kiểm tra hộp thư đến

import imaplib
# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host='mail.example.com')
imap_server.login('[email protected]', '$ecret')
imap_server.select()  # Default is `INBOX`

# Find all emails in inbox and print out the raw email data
_, message_numbers_raw = imap_server.search(None, 'ALL')
for message_number in message_numbers_raw[0].split():
    _, msg = imap_server.fetch(message_number, '(RFC822)')
    print(msg[0][1])

Ví dụ tiếp theo này sẽ chỉ ra cách thực hiện các thao tác phổ biến hơn như

  • Kết nối với máy chủ IMAP
  • Liệt kê các thư mục (hộp thư)
  • Tạo, đổi tên và xóa thư mục (hộp thư)
  • Tìm kiếm email
  • Tìm nạp email
  • Đánh dấu email là đã đọc hoặc chưa đọc
  • Di chuyển một email đến một thư mục khác
  • Xóa một email
import imaplib

# Connect and login to IMAP mail server
username = '[email protected]'
password = 'password'
mail_server = 'mail.example.com'
imap_server = imaplib.IMAP4_SSL(host=mail_server)
imap_server.login(username, password)

# List mailboxes (folders)
response_code, folders = imap_server.list()
print(response_code)  # OK
print('Available folders(mailboxes) to select:')
for folder_details_raw in folders:
    folder_details = folder_details_raw.decode().split()
    print(f'- {folder_details[-1]}')

# Create, rename, and delete mailboxes (folders)
# This format is the one my email provider interserver.net uses
# Create a mailbox
response_code, response_details = imap_server.create('INBOX.myfavorites')
print(response_code)  # `OK` on success or `NO` on failure
print(response_details)  # Create completed/Mailbox already exists
# Rename a mailbox
imap_server.rename('INBOX.myfavorites', 'INBOX.faves')
# Delete a mailbox
imap_server.delete('INBOX.faves')

# Choose the mailbox (folder) to search
# Case sensitive!
imap_server.select('INBOX')  # Default is `INBOX`

# Search for emails in the mailbox that was selected.
# First, you need to search and get the message IDs.
# Then you can fetch specific messages with the IDs.
# Search filters are explained in the RFC at:
# https://tools.ietf.org/html/rfc3501#section-6.4.4
search_criteria = 'ALL'
charset = None  # All
respose_code, message_numbers_raw = imap_server.search(charset, search_criteria)
print(f'Search response: {respose_code}')  # e.g. OK
print(f'Message numbers: {message_numbers_raw}')  # e.g. ['1 2'] A list, with string of message IDs
message_numbers = message_numbers_raw[0].split()

# Fetch full message based on the message numbers obtained from search
for message_number in message_numbers:
    response_code, message_data = imap_server.fetch(message_number, '(RFC822)')
    print(f'Fetch response for message {message_number}: {response_code}')
    print(f'Raw email data:\n{message_data[0][1]}')

    # Mark an email read/unread.
    # Other flags you can set with store() from RFC3501 include: 
    # \Seen \Answered \Flagged \Deleted \Draft \Recent
    imap_server.store(message_number, '+FLAGS', '\SEEN')  # Mark as read
    imap_server.store(message_number, '-FLAGS', '\SEEN')  # Mark as unread

    # Copy an email to a different 
    imap_server.create('INBOX.mykeepers')
    imap_server.copy(message_number, 'INBOX.mykeepers')
    # Delete an email
    imap_server.store(message_number, '+FLAGS', '\Deleted')
    # Expunge after marking emails deleted
    imap_server.expunge()


imap_server.close()
imap_server.logout()

Phân tích nội dung email

Trong ví dụ trước, chúng tôi đã chỉ ra cách tìm nạp dữ liệu email thô, nhưng nó bao gồm các tiêu đề, nội dung và mọi thứ trong một đốm màu duy nhất. Nội dung thô đó tương đương với một thông điệp

import imaplib
# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host='mail.example.com')
imap_server.login('[email protected]', '$ecret')
imap_server.select()  # Default is `INBOX`

# Find all emails in inbox and print out the raw email data
_, message_numbers_raw = imap_server.search(None, 'ALL')
for message_number in message_numbers_raw[0].split():
    _, msg = imap_server.fetch(message_number, '(RFC822)')
    print(msg[0][1])
2. Python có gói
import imaplib
# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host='mail.example.com')
imap_server.login('[email protected]', '$ecret')
imap_server.select()  # Default is `INBOX`

# Find all emails in inbox and print out the raw email data
_, message_numbers_raw = imap_server.search(None, 'ALL')
for message_number in message_numbers_raw[0].split():
    _, msg = imap_server.fetch(message_number, '(RFC822)')
    print(msg[0][1])
3 sẽ phân tích cú pháp dữ liệu thô này và cung cấp cho chúng ta một đối tượng hữu ích

Bạn có thể phân tích cú pháp email bằng email. trình phân tích cú pháp. Ngoài ra còn có một hàm có tên mà bạn có thể sử dụng để phân tích cú pháp trực tiếp từ các byte thô như chúng ta sẽ có. Sau khi có, bạn có thể kiểm tra các khía cạnh khác nhau như xem nó có nhiều phần không, loại nội dung và tải trọng

Ví dụ này sẽ xây dựng dựa trên ví dụ kiểm tra hộp thư đến đơn giản ở trên và trình bày cách

  • Phân tích cú pháp email
    • Truy cập địa chỉ email đến/từ/cc/bcc
    • Nhận phiên bản văn bản thuần túy
    • Nhận phiên bản html
    • Nhận tệp đính kèm
import imaplib
import email

# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host='mail.example.com')
imap_server.login('[email protected]', '$ecret')
imap_server.select()  # Default is `INBOX`

# Find all emails in inbox
_, message_numbers_raw = imap_server.search(None, 'ALL')
for message_number in message_numbers_raw[0].split():
    _, msg = imap_server.fetch(message_number, '(RFC822)')

    # Parse the raw email message in to a convenient object
    message = email.message_from_bytes(msg[0][1])
    print('== Email message =====')
    # print(message)  # print FULL message
    print('== Email details =====')
    print(f'From: {message["from"]}')
    print(f'To: {message["to"]}')
    print(f'Cc: {message["cc"]}')
    print(f'Bcc: {message["bcc"]}')
    print(f'Urgency (1 highest 5 lowest): {message["x-priority"]}')
    print(f'Object type: {type(message)}')
    print(f'Content type: {message.get_content_type()}')
    print(f'Content disposition: {message.get_content_disposition()}')
    print(f'Multipart?: {message.is_multipart()}')
    # If the message is multipart, it basically has multiple emails inside
    # so you must extract each "submail" separately.
    if message.is_multipart():
        print('Multipart types:')
        for part in message.walk():
            print(f'- {part.get_content_type()}')
        multipart_payload = message.get_payload()
        for sub_message in multipart_payload:
            # The actual text/HTML email contents, or attachment data
            print(f'Payload\n{sub_message.get_payload()}')
    else:  # Not a multipart message, payload is simple string
        print(f'Payload\n{message.get_payload()}')
    # You could also use `message.iter_attachments()` to get attachments only

Lưu ý rằng nếu bạn có một email trên đĩa và bạn muốn phân tích cú pháp trực tiếp từ một tệp, bạn có thể sử dụng

import imaplib
# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host='mail.example.com')
imap_server.login('[email protected]', '$ecret')
imap_server.select()  # Default is `INBOX`

# Find all emails in inbox and print out the raw email data
_, message_numbers_raw = imap_server.search(None, 'ALL')
for message_number in message_numbers_raw[0].split():
    _, msg = imap_server.fetch(message_number, '(RFC822)')
    print(msg[0][1])
4 như thế này

from email.parser import BytesParser

with open('some_email.eml', 'rb') as email_file:
    message = BytesParser().parse(email_file)

Nếu bạn chỉ muốn lấy tệp đính kèm từ một email bỏ qua phần thân, bạn có thể sử dụng

Gửi email bằng SMTP

Hãy xem cách gửi email bằng Python. Trước tiên, chúng ta sẽ xem xét việc gửi một email văn bản gốc rất cơ bản bằng cách sử dụng smtplib. Sau đó, chúng tôi sẽ tạo một thông báo email nhiều phần bằng cách sử dụng email. tin nhắn có văn bản, HTML và tệp đính kèm

Những ví dụ này sẽ sử dụng máy chủ SSL SMTP được mã hóa. Cổng mặc định cho SMTP với SSL là 587

  • Cổng 25 - Cổng SMTP không được mã hóa mặc định
  • Cổng 587 - Cổng SSL SMTP được mã hóa mặc định
  • Cổng 465 - Cổng không chuẩn cho SSL SMTP hiếm khi được sử dụng

Lưu ý rằng địa chỉ gửi của bạn có thể rất quan trọng. Một số tường lửa và máy chủ email sẽ ngăn không cho email của bạn đi qua nếu bạn sử dụng tên miền không khớp với máy chủ gửi, vì vậy bạn không thể giả vờ là

import imaplib
# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host='mail.example.com')
imap_server.login('[email protected]', '$ecret')
imap_server.select()  # Default is `INBOX`

# Find all emails in inbox and print out the raw email data
_, message_numbers_raw = imap_server.search(None, 'ALL')
for message_number in message_numbers_raw[0].split():
    _, msg = imap_server.fetch(message_number, '(RFC822)')
    print(msg[0][1])
5

Gửi email văn bản thuần túy

Ví dụ đầu tiên này sẽ hiển thị ví dụ đơn giản nhất về gửi thư bằng SMTP. Email sẽ được tạo thủ công, với các tiêu đề đầu tiên, tiếp theo là một dòng trống, tiếp theo là nội dung văn bản thuần túy

from smtplib import SMTP_SSL, SMTP_SSL_PORT

SMTP_HOST = 'mail.example.com'
SMTP_USER = '[email protected]'
SMTP_PASS = 'Secret!'

# Craft the email by hand
from_email = 'My name '  # or simply the email address
to_emails = ['[email protected]', '[email protected]']
body = "Hello, world!"
headers = f"From: {from_email}\r\n"
headers += f"To: {', '.join(to_emails)}\r\n" 
headers += f"Subject: Hello\r\n"
email_message = headers + "\r\n" + body  # Blank line needed between headers and body

# Connect, authenticate, and send mail
smtp_server = SMTP_SSL(SMTP_HOST, port=SMTP_SSL_PORT)
smtp_server.set_debuglevel(1)  # Show SMTP server interactions
smtp_server.login(SMTP_USER, SMTP_PASS)
smtp_server.sendmail(from_email, to_emails, email_message)

# Disconnect
smtp_server.quit()

Thay vì tạo email dưới dạng chuỗi thô lớn, bạn có thể sử dụng class để quản lý email dễ dàng hơn. Ví dụ này sẽ chỉ ra cách

  • Tạo một đối tượng thư email
  • Đặt đến và đi từ địa chỉ
  • Đặt chủ đề
  • Thêm cờ khẩn cấp
  • Đặt nội dung email
from smtplib import SMTP_SSL, SMTP_SSL_PORT
from email.message import EmailMessage

# Craft the email using email.message.EmailMessage
from_email = 'My name '  # or simply the email address
to_emails = ['[email protected]', '[email protected]']
email_message = EmailMessage()
email_message.add_header('To', ', '.join(to_emails))
email_message.add_header('From', from_email)
email_message.add_header('Subject', 'Hello!')
email_message.add_header('X-Priority', '1')  # Urgency, 1 highest, 5 lowest
email_message.set_content('Hello, world!')

# Connect, authenticate, and send mail
smtp_server = SMTP_SSL('mail.example.com', port=SMTP_SSL_PORT)
smtp_server.set_debuglevel(1)  # Show SMTP server interactions
smtp_server.login('[email protected]', 'pass')
smtp_server.sendmail(from_email, to_emails, email_message.as_bytes())

# Disconnect
smtp_server.quit()

Gửi email HTML nhiều phần có tệp đính kèm

Để tạo một email nhiều phần có chứa các phiên bản văn bản và HTML cùng với tệp đính kèm, bạn có thể sử dụng lớp

email.mime.multipart.MIMEMultipart(_subtype='mixed', boundary=None, _subparts=None, *, policy=compat32, **_params)

Để sử dụng

import imaplib
# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host='mail.example.com')
imap_server.login('[email protected]', '$ecret')
imap_server.select()  # Default is `INBOX`

# Find all emails in inbox and print out the raw email data
_, message_numbers_raw = imap_server.search(None, 'ALL')
for message_number in message_numbers_raw[0].split():
    _, msg = imap_server.fetch(message_number, '(RFC822)')
    print(msg[0][1])
6, trước tiên hãy tạo đối tượng giống như một
import imaplib
# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host='mail.example.com')
imap_server.login('[email protected]', '$ecret')
imap_server.select()  # Default is `INBOX`

# Find all emails in inbox and print out the raw email data
_, message_numbers_raw = imap_server.search(None, 'ALL')
for message_number in message_numbers_raw[0].split():
    _, msg = imap_server.fetch(message_number, '(RFC822)')
    print(msg[0][1])
7 bình thường. Tuy nhiên, thay vì thiết lập nội dung, chúng tôi sẽ
import imaplib
# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host='mail.example.com')
imap_server.login('[email protected]', '$ecret')
imap_server.select()  # Default is `INBOX`

# Find all emails in inbox and print out the raw email data
_, message_numbers_raw = imap_server.search(None, 'ALL')
for message_number in message_numbers_raw[0].split():
    _, msg = imap_server.fetch(message_number, '(RFC822)')
    print(msg[0][1])
8 tất cả các phần, bao gồm phiên bản văn bản, phiên bản html và bất kỳ tệp đính kèm nào

Ví dụ này sẽ chỉ ra cách tạo một email MIME nhiều phần có

  • Phiên bản văn bản thuần túy của email
  • Phiên bản HTML của email
  • tệp đính kèm
from smtplib import SMTP_SSL, SMTP_SSL_PORT
from email.mime.multipart import MIMEMultipart, MIMEBase
from email.mime.text import MIMEText
from email.encoders import encode_base64

from_email = 'My name '  # or simply the email address
to_emails = ['[email protected]', '[email protected]']

# Create multipart MIME email
email_message = MIMEMultipart()
email_message.add_header('To', ', '.join(to_emails))
email_message.add_header('From', from_email)
email_message.add_header('Subject', 'Hello!')
email_message.add_header('X-Priority', '1')  # Urgent/High priority

# Create text and HTML bodies for email
text_part = MIMEText('Hello world plain text!', 'plain')
html_part = MIMEText('

HTML!

', 'html') # Create file attachment attachment = MIMEBase("application", "octet-stream") attachment.set_payload(b'\xDE\xAD\xBE\xEF') # Raw attachment data encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment; filename=myfile.dat") # Attach all the parts to the Multipart MIME email email_message.attach(text_part) email_message.attach(html_part) email_message.attach(attachment) # Connect, authenticate, and send mail smtp_server = SMTP_SSL('mail.example.com', port=SMTP_SSL_PORT) smtp_server.set_debuglevel(1) # Show SMTP server interactions smtp_server.login('[email protected]', 'password') smtp_server.sendmail(from_email, to_emails, email_message.as_bytes()) # Disconnect smtp_server.quit()

Mẫu email với Jinja2

Nếu bạn muốn tạo một mẫu văn bản hoặc HTML để sử dụng lại, tôi khuyên dùng các mẫu Jinja2

Đây là một ví dụ rất cơ bản về cách sử dụng mẫu Jinja2. Tham khảo tài liệu Jinja2 để biết thêm chi tiết

# pip install jinja2
from jinja2 import Template

template = Template('Hello, {{ name }}!')
print(template.render({'name': 'My Name'}))

Gửi tin nhắn văn bản (SMS/MMS) qua email

Hầu hết các nhà cung cấp dịch vụ điện thoại di động cũng cung cấp một cổng email cho phép bạn gửi địa chỉ email và nó sẽ gửi SMS/MMS đến điện thoại di động

Để biết danh sách chi tiết các cổng email SMS được liệt kê bởi nhà cung cấp, hãy xem cổng SMS trên Wikipedia

Ví dụ: để nhắn tin cho số 888-123-4567 trên AT&T, tôi có thể gửi email đến

import imaplib
# Connect to inbox
imap_server = imaplib.IMAP4_SSL(host='mail.example.com')
imap_server.login('[email protected]', '$ecret')
imap_server.select()  # Default is `INBOX`

# Find all emails in inbox and print out the raw email data
_, message_numbers_raw = imap_server.search(None, 'ALL')
for message_number in message_numbers_raw[0].split():
    _, msg = imap_server.fetch(message_number, '(RFC822)')
    print(msg[0][1])
0

Phần kết luận

Sau khi đọc hướng dẫn này, bạn sẽ hiểu cách sử dụng Python để đọc thư bằng IMAP và cách gửi thư bằng SMTP với email văn bản thuần hoặc HTML cùng với tệp đính kèm

Làm cách nào để đọc email bằng IMAP Python?

Trong ví dụ bên dưới, chúng tôi đăng nhập vào máy chủ gmail bằng thông tin đăng nhập của người dùng. Sau đó chúng ta chọn hiển thị các tin nhắn trong hộp thư đến. Một vòng lặp for được sử dụng để hiển thị từng thông báo đã tìm nạp và cuối cùng kết nối bị đóng . Tùy thuộc vào cấu hình hộp thư, thư được hiển thị.

Làm cách nào để đọc dữ liệu từ email bằng Python?

Hãy bắt đầu bằng cách viết một số mã. .
ORG_EMAIL = "@gmail. com" FROM_EMAIL = "Địa chỉ Email của bạn" + ORG_EMAIL FROM_PWD = "Mật khẩu của bạn" SMTP_SERVER = "imap. gmail. com" SMTP_PORT = 993 def read_email_from_gmail(). # logic đọc thư sẽ đến đây
thư = imaplib. .
dữ liệu = thư

Làm cách nào để đọc thư Outlook bằng Python?

Đọc Thư Email Outlook bằng Python . Tải tệp email bằng MailMessage. phương thức tải (tên tệp). Đọc dữ liệu bằng các thuộc tính như chủ đề, nội dung, html_body, v.v.

Sự khác biệt giữa Smtplib và Imaplib là gì?

SMTP VS IMAP . IMAP hoạt động giữa máy chủ và máy khách để liên lạc và SMTP hoạt động giữa các máy chủ để truyền thông tin. IMAP cho phép người dùng sắp xếp email trên máy chủ, trong khi SMTP cho phép sắp xếp email trên bộ nhớ máy khách. IMAP is used to retrieve messages, and SMTP is for sending data. IMAP works between the server and client for communication, and SMTP works between servers to transfer information. IMAP allows users to organize emails onto the server, while SMTP allows organizing emails on client storage.