Python cạo Gmail

Hệ sinh thái phong phú của các mô-đun Python cho phép bạn làm việc nhanh chóng và tích hợp hệ thống của mình hiệu quả hơn. Với Trình kết nối CData Python cho Gmail và khung petl, bạn có thể xây dựng các ứng dụng và quy trình được kết nối với Gmail để trích xuất, chuyển đổi và tải dữ liệu Gmail. Bài viết này cho biết cách kết nối với Gmail bằng Trình kết nối Python CData và sử dụng petl và pandas để trích xuất, chuyển đổi và tải dữ liệu Gmail

Với khả năng xử lý dữ liệu được tối ưu hóa, tích hợp sẵn, Trình kết nối CData Python mang lại hiệu suất chưa từng có để tương tác với dữ liệu Gmail trực tiếp bằng Python. Khi bạn đưa ra các truy vấn SQL phức tạp từ Gmail, trình điều khiển sẽ đẩy trực tiếp các hoạt động SQL được hỗ trợ, chẳng hạn như bộ lọc và tập hợp, tới Gmail và sử dụng công cụ SQL nhúng để xử lý các hoạt động không được hỗ trợ phía máy khách (thường là các hàm SQL và hoạt động THAM GIA)

Kết nối với dữ liệu Gmail

Kết nối với dữ liệu Gmail trông giống như kết nối với bất kỳ nguồn dữ liệu quan hệ nào. Tạo chuỗi kết nối bằng các thuộc tính kết nối được yêu cầu. Đối với bài viết này, bạn sẽ chuyển chuỗi kết nối dưới dạng tham số cho hàm create_engine

Có hai cách để xác thực với Gmail. Trước khi chọn một, trước tiên hãy đảm bảo rằng bạn đã bật quyền truy cập IMAP trong cài đặt tài khoản Gmail của mình. Xem phần "Kết nối với Gmail" trong phần "Bắt đầu" trong tài liệu đã cài đặt để biết hướng dẫn

Thuộc tính Người dùng và Mật khẩu, trong phần Xác thực, có thể được đặt thành thông tin xác thực người dùng Gmail hợp lệ

Ngoài ra, thay vì cung cấp Mật khẩu, bạn có thể sử dụng tiêu chuẩn xác thực OAuth. Để thay mặt người dùng cá nhân truy cập các API của Google, bạn có thể sử dụng thông tin đăng nhập được nhúng hoặc bạn có thể đăng ký ứng dụng OAuth của riêng mình

OAuth cũng cho phép bạn sử dụng tài khoản dịch vụ để thay mặt người dùng kết nối trong miền Google Apps. Để xác thực bằng tài khoản dịch vụ, bạn sẽ cần đăng ký một ứng dụng để nhận các giá trị OAuth JWT

Ngoài các giá trị OAuth, bạn sẽ cần cung cấp cho Người dùng. Xem chương "Bắt đầu" trong tài liệu trợ giúp để biết hướng dẫn sử dụng OAuth

Sau khi cài đặt Trình kết nối Gmail CData, hãy làm theo quy trình bên dưới để cài đặt các mô-đun cần thiết khác và bắt đầu truy cập Gmail thông qua các đối tượng Python

Cài đặt các mô-đun cần thiết

Sử dụng tiện ích pip để cài đặt các mô-đun và khung cần thiết

pip install petl
pip install pandas

Xây dựng ứng dụng ETL cho dữ liệu Gmail bằng Python

Khi các mô-đun và khung cần thiết được cài đặt, chúng tôi đã sẵn sàng xây dựng ứng dụng ETL của mình. Đoạn mã sau, nhưng mã nguồn đầy đủ có sẵn ở cuối bài viết

Trước tiên, hãy đảm bảo nhập các mô-đun (bao gồm cả Trình kết nối CData) với thông tin sau

import petl as etl
import pandas as pd
import cdata.gmail as mod

Bây giờ bạn có thể kết nối với một chuỗi kết nối. Sử dụng chức năng kết nối cho CData Gmail Connector để tạo kết nối làm việc với dữ liệu Gmail

cnxn = mod.connect("User=username;Password=password;")

Tạo câu lệnh SQL để truy vấn Gmail

Sử dụng SQL để tạo câu lệnh truy vấn Gmail. Trong bài viết này, chúng tôi đọc dữ liệu từ thực thể Hộp thư đến

sql = "SELECT Subject, Size FROM Inbox WHERE From = '[email protected]'"

Trích xuất, chuyển đổi và tải dữ liệu Gmail

Với kết quả truy vấn được lưu trữ trong DataFrame, chúng tôi có thể sử dụng petl để trích xuất, chuyển đổi và tải dữ liệu Gmail. Trong ví dụ này, chúng tôi trích xuất dữ liệu Gmail, sắp xếp dữ liệu theo cột Kích thước và tải dữ liệu vào tệp CSV

Đang tải dữ liệu Gmail vào tệp CSV

table1 = etl.fromdb(cnxn,sql)

table2 = etl.sort(table1,'Size')

etl.tocsv(table2,'inbox_data.csv')

Trong ví dụ sau, chúng tôi thêm các hàng mới vào bảng Hộp thư đến

Thêm hàng mới vào Gmail

table1 = [ ['Subject','Size'], ['NewSubject1','NewSize1'], ['NewSubject2','NewSize2'], ['NewSubject3','NewSize3'] ]

etl.appenddb(table1, cnxn, 'Inbox')

Với Trình kết nối CData Python dành cho Gmail, bạn có thể làm việc với dữ liệu Gmail giống như cách bạn làm với bất kỳ cơ sở dữ liệu nào, bao gồm quyền truy cập trực tiếp vào dữ liệu trong các gói ETL như petl

Dùng thử miễn phí và biết thêm thông tin

Tải xuống bản dùng thử Gmail Python Connector miễn phí trong 30 ngày để bắt đầu xây dựng các ứng dụng và tập lệnh Python có khả năng kết nối với dữ liệu Gmail. Hãy liên hệ với Nhóm hỗ trợ của chúng tôi nếu bạn có bất kỳ câu hỏi nào

Gmail là dịch vụ mail phổ biến nhất hiện nay. Cá nhân, tổ chức sử dụng. Nhiều tính năng của nó được tăng cường bằng AI, bao gồm bảo mật (và phát hiện email lừa đảo) và các đề xuất khi viết email

Trong các hướng dẫn trước, chúng tôi đã giải thích cách bạn có thể gửi và đọc email bằng Python. Nếu bạn chưa đọc chúng, tôi thực sự khuyên bạn nên xem chúng

Mặc dù các hướng dẫn trước đây là sử dụng trực tiếp các giao thức IMAP/SMTP, nhưng trong hướng dẫn này, chúng ta sẽ sử dụng API của Google để gửi và đọc email;

Đối với hướng dẫn này, chúng tôi sẽ khám phá một số tính năng chính của API Gmail và chúng tôi sẽ viết một số tập lệnh Python có thể gửi email, tìm kiếm email, xóa và đánh dấu chúng là đã đọc hoặc chưa đọc. Chúng sẽ được sử dụng như sau

$ python send_emails.py [email protected] "Subject" "Message body" --files file1.txt file2.pdf file3.png
$ python read_emails.py "search query"
$ python delete_emails.py "search query"
$ python mark_emails.py --read "search query"
$ python mark_emails.py --unread "search query"

Đây là mục lục

Để bắt đầu, hãy cài đặt các phụ thuộc cần thiết

$ pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Kích hoạt API Gmail

Để sử dụng API Gmail, chúng tôi cần có mã thông báo để kết nối với API của Gmail. Chúng tôi có thể lấy một cái từ bảng điều khiển của Google API

Trước tiên, chúng tôi kích hoạt API thư của Google, đi tới bảng điều khiển và sử dụng thanh tìm kiếm để tìm kiếm API Gmail, nhấp vào nó và sau đó bật

Python cạo Gmail

Sau đó, chúng tôi tạo một OAuth 2. 0 ID khách hàng bằng cách tạo thông tin xác thực (bằng cách chuyển đến nút Tạo thông tin xác thực)

Python cạo Gmail

Nhấp vào Tạo thông tin xác thực, sau đó chọn ID ứng dụng khách OAuth từ menu thả xuống

Python cạo Gmail

Bạn sẽ được dẫn đến trang này

Python cạo Gmail
Chọn Ứng dụng máy tính để bàn làm loại Ứng dụng và tiếp tục. Bạn sẽ thấy một cửa sổ như thế này

Python cạo Gmail

Hãy tiếp tục và nhấp vào TẢI XUỐNG JSON; . Đổi tên nó thành

import os
import pickle
# Gmail API utils
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# for encoding/decoding messages in base64
from base64 import urlsafe_b64decode, urlsafe_b64encode
# for dealing with attachement MIME types
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from mimetypes import guess_type as guess_mime_type

# Request all access (permission to read/send/receive emails, manage the inbox, and more)
SCOPES = ['https://mail.google.com/']
our_email = '[email protected]'
0 và đặt nó vào thư mục hiện tại của dự án

Ngoài ra, nếu bạn bỏ lỡ cửa sổ đó, bạn có thể nhấp vào nút biểu tượng tải xuống đó ở bên phải trang

Python cạo Gmail

Ghi chú. Nếu đây là lần đầu tiên bạn sử dụng Google API, bạn có thể chỉ cần tạo màn hình Đồng ý OAuth và thêm email của mình làm người dùng thử nghiệm

Bây giờ chúng ta đã hoàn tất việc thiết lập API, hãy bắt đầu bằng cách nhập các mô-đun cần thiết

________số 8_______

Rõ ràng, bạn cần thay đổi

import os
import pickle
# Gmail API utils
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# for encoding/decoding messages in base64
from base64 import urlsafe_b64decode, urlsafe_b64encode
# for dealing with attachement MIME types
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from mimetypes import guess_type as guess_mime_type

# Request all access (permission to read/send/receive emails, manage the inbox, and more)
SCOPES = ['https://mail.google.com/']
our_email = '[email protected]'
1 thành địa chỉ của bạn. Đảm bảo bạn sử dụng email mà bạn đã tạo API auth

Trước hết, hãy tạo một hàm tải

import os
import pickle
# Gmail API utils
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# for encoding/decoding messages in base64
from base64 import urlsafe_b64decode, urlsafe_b64encode
# for dealing with attachement MIME types
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from mimetypes import guess_type as guess_mime_type

# Request all access (permission to read/send/receive emails, manage the inbox, and more)
SCOPES = ['https://mail.google.com/']
our_email = '[email protected]'
0, thực hiện xác thực bằng Gmail API và trả về một đối tượng dịch vụ có thể được sử dụng sau này trong tất cả các hàm sắp tới của chúng ta

def gmail_authenticate():
    creds = None
    # the file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first time
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)
    # if there are no (valid) credentials availablle, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # save the credentials for the next run
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)
    return build('gmail', 'v1', credentials=creds)

# get the Gmail API service
service = gmail_authenticate()

Bạn sẽ thấy điều này quen thuộc nếu trước đây bạn đã sử dụng Google API, chẳng hạn như Google Drive API;

Thao tác này sẽ nhắc bạn trong trình duyệt mặc định của mình chấp nhận các quyền cần thiết cho ứng dụng này. Nếu bạn thấy một cửa sổ cho biết ứng dụng chưa được xác minh, bạn có thể chỉ cần chuyển đến Nâng cao và nhấp vào đi tới Gmail API Python (không an toàn)

Gửi e-mail

Đầu tiên, hãy bắt đầu với chức năng gửi email; . Một tin nhắn là một phiên bản của

import os
import pickle
# Gmail API utils
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# for encoding/decoding messages in base64
from base64 import urlsafe_b64decode, urlsafe_b64encode
# for dealing with attachement MIME types
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from mimetypes import guess_type as guess_mime_type

# Request all access (permission to read/send/receive emails, manage the inbox, and more)
SCOPES = ['https://mail.google.com/']
our_email = '[email protected]'
5 (hoặc
import os
import pickle
# Gmail API utils
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# for encoding/decoding messages in base64
from base64 import urlsafe_b64decode, urlsafe_b64encode
# for dealing with attachement MIME types
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from mimetypes import guess_type as guess_mime_type

# Request all access (permission to read/send/receive emails, manage the inbox, and more)
SCOPES = ['https://mail.google.com/']
our_email = '[email protected]'
6, nếu nó không chứa tệp đính kèm)

# Adds the attachment with the given filename to the given message
def add_attachment(message, filename):
    content_type, encoding = guess_mime_type(filename)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(filename, 'rb')
        msg = MIMEText(fp.read().decode(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(filename, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(filename, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(filename, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(filename)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

Thứ hai, chúng tôi viết một hàm lấy một số tham số tin nhắn, xây dựng và trả về một tin nhắn email

def build_message(destination, obj, body, attachments=[]):
    if not attachments: # no attachments given
        message = MIMEText(body)
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
    else:
        message = MIMEMultipart()
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
        message.attach(MIMEText(body))
        for filename in attachments:
            add_attachment(message, filename)
    return {'raw': urlsafe_b64encode(message.as_bytes()).decode()}

Và cuối cùng, chúng tôi tạo một hàm nhận tham số thư và sử dụng API thư của Google để gửi thư được tạo bằng

import os
import pickle
# Gmail API utils
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# for encoding/decoding messages in base64
from base64 import urlsafe_b64decode, urlsafe_b64encode
# for dealing with attachement MIME types
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from mimetypes import guess_type as guess_mime_type

# Request all access (permission to read/send/receive emails, manage the inbox, and more)
SCOPES = ['https://mail.google.com/']
our_email = '[email protected]'
7 mà chúng tôi đã xác định trước đó

def send_message(service, destination, obj, body, attachments=[]):
    return service.users().messages().send(
      userId="me",
      body=build_message(destination, obj, body, attachments)
    ).execute()

Đó là để gửi tin nhắn. Hãy sử dụng chức năng để gửi một email mẫu

# test send email
send_message(service, "[email protected]", "This is a subject", 
            "This is the body of the email", ["test.txt", "anyfile.png"])

Đặt email của bạn làm địa chỉ đích và đường dẫn thực đến tệp và bạn sẽ thấy rằng thư thực sự đã được gửi

học cũng được. Cách gửi email bằng Python bằng smtplib

Tìm kiếm Email

def search_messages(service, query):
    result = service.users().messages().list(userId='me',q=query).execute()
    messages = [ ]
    if 'messages' in result:
        messages.extend(result['messages'])
    while 'nextPageToken' in result:
        page_token = result['nextPageToken']
        result = service.users().messages().list(userId='me',q=query, pageToken=page_token).execute()
        if 'messages' in result:
            messages.extend(result['messages'])
    return messages

Chúng tôi phải truy xuất từng trang tin nhắn vì chúng được đánh số trang. Hàm này sẽ trả về ID của các email khớp với truy vấn. Chúng tôi sẽ sử dụng nó để xóa, đánh dấu là đã đọc, đánh dấu là chưa đọc và các tính năng tìm kiếm. Tin vui là bạn có thể sử dụng các toán tử tìm kiếm trong Gmail chẳng hạn như

import os
import pickle
# Gmail API utils
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# for encoding/decoding messages in base64
from base64 import urlsafe_b64decode, urlsafe_b64encode
# for dealing with attachement MIME types
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from mimetypes import guess_type as guess_mime_type

# Request all access (permission to read/send/receive emails, manage the inbox, and more)
SCOPES = ['https://mail.google.com/']
our_email = '[email protected]'
8,
import os
import pickle
# Gmail API utils
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# for encoding/decoding messages in base64
from base64 import urlsafe_b64decode, urlsafe_b64encode
# for dealing with attachement MIME types
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from mimetypes import guess_type as guess_mime_type

# Request all access (permission to read/send/receive emails, manage the inbox, and more)
SCOPES = ['https://mail.google.com/']
our_email = '[email protected]'
9,
def gmail_authenticate():
    creds = None
    # the file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first time
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)
    # if there are no (valid) credentials availablle, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # save the credentials for the next run
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)
    return build('gmail', 'v1', credentials=creds)

# get the Gmail API service
service = gmail_authenticate()
0,
def gmail_authenticate():
    creds = None
    # the file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first time
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)
    # if there are no (valid) credentials availablle, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # save the credentials for the next run
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)
    return build('gmail', 'v1', credentials=creds)

# get the Gmail API service
service = gmail_authenticate()
1,
def gmail_authenticate():
    creds = None
    # the file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first time
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)
    # if there are no (valid) credentials availablle, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # save the credentials for the next run
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)
    return build('gmail', 'v1', credentials=creds)

# get the Gmail API service
service = gmail_authenticate()
2 và
def gmail_authenticate():
    creds = None
    # the file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first time
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)
    # if there are no (valid) credentials availablle, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # save the credentials for the next run
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)
    return build('gmail', 'v1', credentials=creds)

# get the Gmail API service
service = gmail_authenticate()
3 (đối với ngày tháng), v.v. Kiểm tra trang này để biết thêm thông tin

đọc email

Trong phần này, chúng ta sẽ tạo mã Python lấy truy vấn tìm kiếm làm đầu vào và đọc tất cả các email phù hợp;

Chúng tôi cũng sẽ tạo một thư mục cho mỗi email dựa trên chủ đề và tải xuống nội dung

def gmail_authenticate():
    creds = None
    # the file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first time
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)
    # if there are no (valid) credentials availablle, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # save the credentials for the next run
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)
    return build('gmail', 'v1', credentials=creds)

# get the Gmail API service
service = gmail_authenticate()
9 cũng như bất kỳ tệp nào được đính kèm trong email và lưu nó trong thư mục đã tạo

Trước khi chúng tôi đi sâu vào chức năng đọc email được cung cấp cho một truy vấn tìm kiếm, chúng tôi sẽ xác định hai chức năng tiện ích mà chúng tôi sẽ sử dụng

# utility functions
def get_size_format(b, factor=1024, suffix="B"):
    """
    Scale bytes to its proper byte format
    e.g:
        1253656 => '1.20MB'
        1253656678 => '1.17GB'
    """
    for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
        if b < factor:
            return f"{b:.2f}{unit}{suffix}"
        b /= factor
    return f"{b:.2f}Y{suffix}"


def clean(text):
    # clean text for creating a folder
    return "".join(c if c.isalnum() else "_" for c in text)

Hàm

# Adds the attachment with the given filename to the given message
def add_attachment(message, filename):
    content_type, encoding = guess_mime_type(filename)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(filename, 'rb')
        msg = MIMEText(fp.read().decode(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(filename, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(filename, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(filename, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(filename)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
0 sẽ chỉ in các byte ở định dạng đẹp (được lấy từ hướng dẫn này) và chúng ta sẽ cần hàm
# Adds the attachment with the given filename to the given message
def add_attachment(message, filename):
    content_type, encoding = guess_mime_type(filename)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(filename, 'rb')
        msg = MIMEText(fp.read().decode(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(filename, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(filename, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(filename, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(filename)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
1 để tạo tên thư mục không chứa khoảng trắng và ký tự đặc biệt

Tiếp theo, hãy định nghĩa một hàm phân tích nội dung của phân vùng email

$ pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
0

Bây giờ, hãy viết chức năng chính của chúng tôi để đọc email

$ pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
1

Vì chức năng được xác định trước đó

# Adds the attachment with the given filename to the given message
def add_attachment(message, filename):
    content_type, encoding = guess_mime_type(filename)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(filename, 'rb')
        msg = MIMEText(fp.read().decode(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(filename, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(filename, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(filename, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(filename)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
2 trả về danh sách ID của các email phù hợp, nên
# Adds the attachment with the given filename to the given message
def add_attachment(message, filename):
    content_type, encoding = guess_mime_type(filename)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(filename, 'rb')
        msg = MIMEText(fp.read().decode(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(filename, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(filename, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(filename, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(filename)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
3 tải xuống nội dung của email và thực hiện những gì đã đề cập ở trên

Hàm

# Adds the attachment with the given filename to the given message
def add_attachment(message, filename):
    content_type, encoding = guess_mime_type(filename)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(filename, 'rb')
        msg = MIMEText(fp.read().decode(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(filename, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(filename, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(filename, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(filename)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
3 sử dụng
# Adds the attachment with the given filename to the given message
def add_attachment(message, filename):
    content_type, encoding = guess_mime_type(filename)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(filename, 'rb')
        msg = MIMEText(fp.read().decode(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(filename, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(filename, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(filename, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(filename)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
5 để phân tích các phân vùng email khác nhau, nếu là
# Adds the attachment with the given filename to the given message
def add_attachment(message, filename):
    content_type, encoding = guess_mime_type(filename)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(filename, 'rb')
        msg = MIMEText(fp.read().decode(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(filename, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(filename, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(filename, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(filename)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
6 thì chúng ta chỉ cần giải mã và in ra màn hình;

Ngoài ra, nếu hai email có cùng

def gmail_authenticate():
    creds = None
    # the file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first time
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)
    # if there are no (valid) credentials availablle, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # save the credentials for the next run
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)
    return build('gmail', 'v1', credentials=creds)

# get the Gmail API service
service = gmail_authenticate()
6, thì chúng tôi cần thêm một bộ đếm đơn giản vào tên của thư mục và đó là những gì chúng tôi đã làm với
def build_message(destination, obj, body, attachments=[]):
    if not attachments: # no attachments given
        message = MIMEText(body)
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
    else:
        message = MIMEMultipart()
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
        message.attach(MIMEText(body))
        for filename in attachments:
            add_attachment(message, filename)
    return {'raw': urlsafe_b64encode(message.as_bytes()).decode()}
1

Hãy sử dụng điều này trong hành động

$ pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
2

Điều này sẽ tải xuống và phân tích cú pháp tất cả các email có chứa từ khóa Mã Python. Đây là một phần của đầu ra

$ pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
3

Bạn cũng sẽ thấy các thư mục được tạo trong thư mục hiện tại của mình cho mỗi email phù hợp

Bên trong mỗi thư mục là phiên bản HTML tương ứng của email và bất kỳ tệp đính kèm nào, nếu có

Bạn có thể sử dụng các bộ lọc nâng cao trong hàm

# Adds the attachment with the given filename to the given message
def add_attachment(message, filename):
    content_type, encoding = guess_mime_type(filename)
    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(filename, 'rb')
        msg = MIMEText(fp.read().decode(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(filename, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(filename, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(filename, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(filename)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)
2. Ví dụ: nếu bạn muốn nhận email có tệp đính kèm PDF, bạn có thể sử dụng
def build_message(destination, obj, body, attachments=[]):
    if not attachments: # no attachments given
        message = MIMEText(body)
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
    else:
        message = MIMEMultipart()
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
        message.attach(MIMEText(body))
        for filename in attachments:
            add_attachment(message, filename)
    return {'raw': urlsafe_b64encode(message.as_bytes()).decode()}
3. Một lần nữa, hãy kiểm tra trang này để lọc nâng cao

Có liên quan. Cách đọc email bằng Python bằng imaplib

Đánh dấu email là đã đọc

$ pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
4

Chúng tôi sử dụng phương thức 

def build_message(destination, obj, body, attachments=[]):
    if not attachments: # no attachments given
        message = MIMEText(body)
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
    else:
        message = MIMEMultipart()
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
        message.attach(MIMEText(body))
        for filename in attachments:
            add_attachment(message, filename)
    return {'raw': urlsafe_b64encode(message.as_bytes()).decode()}
4 và chúng tôi đặt
def build_message(destination, obj, body, attachments=[]):
    if not attachments: # no attachments given
        message = MIMEText(body)
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
    else:
        message = MIMEMultipart()
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
        message.attach(MIMEText(body))
        for filename in attachments:
            add_attachment(message, filename)
    return {'raw': urlsafe_b64encode(message.as_bytes()).decode()}
5 thành 
def build_message(destination, obj, body, attachments=[]):
    if not attachments: # no attachments given
        message = MIMEText(body)
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
    else:
        message = MIMEMultipart()
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
        message.attach(MIMEText(body))
        for filename in attachments:
            add_attachment(message, filename)
    return {'raw': urlsafe_b64encode(message.as_bytes()).decode()}
6 trong tham số
def build_message(destination, obj, body, attachments=[]):
    if not attachments: # no attachments given
        message = MIMEText(body)
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
    else:
        message = MIMEMultipart()
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
        message.attach(MIMEText(body))
        for filename in attachments:
            add_attachment(message, filename)
    return {'raw': urlsafe_b64encode(message.as_bytes()).decode()}
7 để xóa nhãn chưa đọc khỏi các email trùng khớp

Ví dụ: hãy đánh dấu tất cả các email của Google là đã đọc

$ pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
5

Đánh dấu email là chưa đọc

Đánh dấu thư là chưa đọc có thể được thực hiện theo cách tương tự, lần này bằng cách thêm nhãn

def build_message(destination, obj, body, attachments=[]):
    if not attachments: # no attachments given
        message = MIMEText(body)
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
    else:
        message = MIMEMultipart()
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
        message.attach(MIMEText(body))
        for filename in attachments:
            add_attachment(message, filename)
    return {'raw': urlsafe_b64encode(message.as_bytes()).decode()}
6

$ pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
6

chạy ví dụ

$ pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
7

Xóa Email

Bây giờ, đối với tính năng xóa tin nhắn

$ pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
8

Lần này, chúng tôi sử dụng phương pháp

def build_message(destination, obj, body, attachments=[]):
    if not attachments: # no attachments given
        message = MIMEText(body)
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
    else:
        message = MIMEMultipart()
        message['to'] = destination
        message['from'] = our_email
        message['subject'] = obj
        message.attach(MIMEText(body))
        for filename in attachments:
            add_attachment(message, filename)
    return {'raw': urlsafe_b64encode(message.as_bytes()).decode()}
9 để xóa tất cả các email phù hợp, ví dụ: hãy xóa tất cả email Google Alerts

$ pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
9

Có liên quan. Cách xóa email trong Python bằng imaplib

Phần kết luận

Truy vấn Gmail hỗ trợ các bộ lọc có thể được sử dụng để chọn các thư cụ thể. Một số bộ lọc này được hiển thị bên dưới và đây là hộp thoại được hiển thị khi tìm kiếm email;

Python cạo Gmail

Gmail không chỉ cung cấp một giao diện người dùng tuyệt vời và thân thiện với nhiều tính năng dành cho những người dùng khó tính mà còn cung cấp một API mạnh mẽ để các nhà phát triển sử dụng và tương tác với Gmail. Chúng tôi kết luận rằng thao tác gửi email từ Google mail theo lập trình là rất đơn giản

Nếu bạn muốn biết thêm về API, tôi khuyên bạn nên kiểm tra trang Gmail API chính thức

Cuối cùng, tôi đã tạo các tập lệnh Python cho từng tác vụ mà chúng tôi đã thực hiện trong hướng dẫn này;

Làm cách nào để xóa Gmail bằng Python?

Cấu trúc mã Python .
Nhập thư viện cần thiết
Nhập các biến mã hóa cứng
Tạo chức năng cho. Tạo logic tìm kiếm của Hộp thư đến của chúng tôi. Truy cập nội dung của một email cụ thể để truy cập tệp để tải xuống. Lưu tệp đã cho

Bạn có thể cạo email Gmail không?

Quét dữ liệu Gmail . Điều này hữu ích nếu bạn cần kiểm tra email của chính mình trong cài đặt có lập trình hoặc tự động, cho phép bạn tìm kiếm văn bản, nhãn cụ thể, v.v.. trong Gmail và truy cập nội dung email từ API của họ. Gmail offers an official API you can use to access your own emails. This is useful if you need to check your own emails in a programmatic or automated setting, allowing you to search for specific text, labels, etc… in Gmail and access the email content from their API.

Làm cách nào để trích xuất nội dung email bằng Python?

Để trích xuất email từ văn bản, chúng ta có thể lấy biểu thức chính quy . Trong ví dụ dưới đây, chúng tôi sử dụng gói biểu thức chính quy để xác định mẫu ID email và sau đó sử dụng hàm findall() để truy xuất những văn bản khớp với mẫu này.

Làm cách nào để sử dụng API Gmail với Python?

Nếu bạn chưa quen với việc xác thực và ủy quyền cho API Google Workspace, hãy đọc phần Tổng quan về xác thực và ủy quyền. Tạo một ứng dụng dòng lệnh Python đưa ra các yêu cầu đối với API Gmail. .
Thiết lập môi trường của bạn
Cài đặt thư viện máy khách
thiết lập mẫu
Chạy mẫu