📅  最后修改于: 2023-12-03 15:21:52.613000             🧑  作者: Mango
使用 Python 语言编写程序,可以轻松地从 Gmail 中读取电子邮件。通过这种方式,可以将 Gmail 中接收的大量邮件自动化处理,节省大量时间。
在开始编写 Python 代码之前,需要安装 Google API 客户端库。可以通过以下代码安装:
!pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
为了从 Gmail 中读取电子邮件,需要获得 Google API 令牌。以下是获取 Google API 令牌的步骤:
在安装 Google API 客户端库并获得 Google API 令牌之后,现在可以编写 Python 代码以从 Gmail 中读取电子邮件。以下是代码片段:
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import os
import urllib.request
# Load credentials from the saved session
creds = Credentials.from_authorized_user_file("token.json", scopes)
# Use Gmail API
service = build("gmail", "v1", credentials=creds)
# Get a list of messages from the Gmail inbox
def get_messages():
try:
messages = []
result = service.users().messages().list(userId='me').execute()
messages.extend(result['messages'])
while 'nextPageToken' in result:
page_token = result['nextPageToken']
result = service.users().messages().list(userId='me', pageToken=page_token).execute()
messages.extend(result['messages'])
return messages
except HttpError as error:
print('An error occurred: %s' % error)
return None
# Get message content from message ID
def get_message(message_id):
try:
message = service.users().messages().get(userId='me', id=message_id).execute()
for part in message['payload']['parts']:
if part['filename']:
if 'data' in part:
data = part['data']
else:
att_id = part['body']['attachmentId']
att = service.users().messages().attachments().get(userId='me', messageId=message['id'], id=att_id).execute()
data = att['data']
file_data = base64.urlsafe_b64decode(data.encode('UTF-8'))
path = part['filename']
with open(path, 'wb') as f:
f.write(file_data)
return message
except HttpError as error:
print('An error occurred: %s' % error)
return None
在编写 Python 代码之后,现在可以执行程序。以下是代码片段:
messages = get_messages()
if messages is not None:
for message in messages:
message_id = message['id']
message_content = get_message(message_id)
使用 Python 语言编写程序,可以轻松地从 Gmail 中读取电子邮件。这种方式可以将 Gmail 中接收的大量邮件自动化处理,节省大量时间。