要使用Python和Gmail API发送带有多个附件的消息,您可以按照以下步骤进行操作:
google-api-python-client
库,这是与Gmail API交互所需的库。您可以使用以下命令进行安装:pip install google-api-python-client
import base64
import mimetypes
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google.oauth2.credentials import Credentials
# 使用之前设置好的API凭据文件授权访问
credentials = Credentials.from_authorized_user_file('credentials.json', ['https://www.googleapis.com/auth/gmail.compose'])
service = build('gmail', 'v1', credentials=credentials)
def create_message_with_attachments(sender, to, subject, message_text, file_paths):
message = MIMEMultipart()
message['to'] = to
message['from'] = sender
message['subject'] = subject
message.attach(MIMEText(message_text, 'plain'))
for file_path in file_paths:
content_type, encoding = mimetypes.guess_type(file_path)
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':
with open(file_path, 'r') as file:
attachment = MIMEText(file.read(), _subtype=sub_type)
elif main_type == 'image':
with open(file_path, 'rb') as file:
attachment = MIMEImage(file.read(), _subtype=sub_type)
elif main_type == 'audio':
with open(file_path, 'rb') as file:
attachment = MIMEAudio(file.read(), _subtype=sub_type)
else:
with open(file_path, 'rb') as file:
attachment = MIMEBase(main_type, sub_type)
attachment.set_payload(file.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_path))
message.attach(attachment)
return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def send_message(service, user_id, message):
try:
message = service.users().messages().send(userId=user_id, body=message).execute()
print('Message sent! Message ID: %s' % message['id'])
return message
except HttpError as error:
print('An error occurred: %s' % error)
sender = 'your_email@gmail.com'
to = 'recipient@example.com'
subject = 'This is the subject'
message_text = 'This is the message body'
file_paths = ['path/to/file1.txt', 'path/to/file2.jpg', 'path/to/file3.mp3']
message = create_message_with_attachments(sender, to, subject, message_text, file_paths)
send_message(service, 'me', message)
请注意,上述代码中的'credentials.json'
应为您之前设置的API凭据文件的路径,'path/to/file1.txt'
等应为您要发送的附件文件的实际路径。
以上是使用Python和Gmail API发送带有多个附件的消息的步骤。如果您想了解更多关于Gmail API的信息,请参考腾讯云的《Gmail API》文档。
领取专属 10元无门槛券
手把手带您无忧上云