使用Gmail API发送大于10MB的附件,可以通过以下步骤实现:
import base64
import mimetypes
import os
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google.oauth2 import service_account
from googleapiclient.http import MediaFileUpload
# 设置凭据文件的路径
credentials_path = '/path/to/credentials.json'
# 创建Gmail API的服务对象
credentials = service_account.Credentials.from_service_account_file(credentials_path, scopes=['https://www.googleapis.com/auth/gmail.compose'])
service = build('gmail', 'v1', credentials=credentials)
def send_email_with_large_attachment(sender, to, subject, message_text, attachment_path):
try:
# 创建邮件主体
message = create_message_with_attachment(sender, to, subject, message_text, attachment_path)
# 发送邮件
send_message(message)
print("邮件发送成功!")
except HttpError as error:
print("邮件发送失败:{}".format(error))
def create_message_with_attachment(sender, to, subject, message_text, attachment_path):
# 创建邮件主体
message = create_message(sender, to, subject, message_text)
# 添加附件
message = add_attachment_to_message(message, attachment_path)
return message
def create_message(sender, to, subject, message_text):
# 创建邮件主体
message = {
'from': sender,
'to': to,
'subject': subject,
'text': message_text
}
return message
def add_attachment_to_message(message, attachment_path):
# 获取附件的文件名和MIME类型
filename = os.path.basename(attachment_path)
content_type, encoding = mimetypes.guess_type(attachment_path)
# 如果MIME类型无法识别,则默认为二进制流
if content_type is None or encoding is not None:
content_type = 'application/octet-stream'
# 读取附件内容并进行Base64编码
with open(attachment_path, 'rb') as file:
attachment_data = file.read()
attachment_data_base64 = base64.urlsafe_b64encode(attachment_data).decode('utf-8')
# 创建附件对象
attachment = {
'filename': filename,
'mimeType': content_type,
'data': attachment_data_base64
}
# 将附件添加到邮件主体中
message['attachments'] = [attachment]
return message
def send_message(message):
# 发送邮件
service.users().messages().send(userId='me', body=message).execute()
# 使用示例
sender = 'your_email@gmail.com'
to = 'recipient@example.com'
subject = '邮件主题'
message_text = '邮件正文'
attachment_path = '/path/to/attachment.pdf'
send_email_with_large_attachment(sender, to, subject, message_text, attachment_path)
在上述示例代码中,你需要将credentials_path
设置为你下载的JSON凭据文件的路径,并提供发送者、收件人、邮件主题、邮件正文和附件的相关信息。然后,调用send_email_with_large_attachment
函数即可发送带有大附件的邮件。
值得注意的是,Gmail API对附件大小有限制,最大为25MB。如果你的附件超过了这个限制,你可以考虑使用Google Drive API来上传附件到Google Drive,并在邮件中包含附件的链接。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云