在没有访问令牌或重定向的情况下使用Gmail API发送带有附件的消息,可以通过使用服务账号进行身份验证和授权来实现。以下是详细步骤:
以下是一个使用Python和google-api-python-client库的示例代码:
import os
import base64
from googleapiclient.discovery import build
from google.oauth2 import service_account
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
# 服务账号的JSON密钥文件路径
credentials_file = 'path/to/credentials.json'
# 创建服务账号凭据
credentials = service_account.Credentials.from_service_account_file(
credentials_file, scopes=['https://www.googleapis.com/auth/gmail.compose'])
# 创建Gmail API客户端实例
service = build('gmail', 'v1', credentials=credentials)
def create_message_with_attachment(sender, to, subject, message_text, file_path):
message = MIMEMultipart()
message['to'] = to
message['from'] = sender
message['subject'] = subject
msg = MIMEText(message_text)
message.attach(msg)
# 添加附件
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(open(file_path, 'rb').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 Exception as e:
print('An error occurred: %s' % e)
return None
# 发送带有附件的消息
sender = 'your-email@gmail.com'
to = 'recipient@example.com'
subject = 'Test Email with Attachment'
message_text = 'This is a test email with attachment.'
attachment_file = 'path/to/attachment.pdf'
message = create_message_with_attachment(sender, to, subject, message_text, attachment_file)
send_message(service, 'me', message)
请注意,上述示例代码仅为参考,您需要根据实际情况进行适当的修改和调整。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses)
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云