在Python中使用Gmail API而无需打开浏览器,可以通过使用Google的google-auth
和google-auth-oauthlib
库来实现。以下是一个完整的示例代码,用于使用Gmail API发送电子邮件:
import os
import base64
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email import encoders
# 定义要发送的邮件内容
sender = 'your-email@gmail.com'
receiver = 'recipient-email@example.com'
subject = 'Test Email'
message = 'This is a test email sent using Gmail API.'
# 定义附件文件路径
attachment_path = 'path/to/attachment.pdf'
# 定义Gmail API的访问范围
SCOPES = ['https://www.googleapis.com/auth/gmail.compose']
# 通过OAuth2进行身份验证并获取凭据
def get_credentials():
creds = None
# 存储凭据的文件路径
token_file = 'path/to/token.json'
# 存储OAuth2客户端密钥的文件路径
credentials_file = 'path/to/credentials.json'
if os.path.exists(token_file):
creds = Credentials.from_authorized_user_file(token_file, SCOPES)
# 如果没有有效的凭据,则从客户端密钥文件进行身份验证
if not creds or not creds.valid:
flow = InstalledAppFlow.from_client_secrets_file(credentials_file, SCOPES)
creds = flow.run_local_server(port=0)
# 保存凭据以便下次使用
with open(token_file, 'w') as token:
token.write(creds.to_json())
return creds
def create_message(sender, receiver, subject, message, attachment_path=None):
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
if attachment_path:
with open(attachment_path, 'rb') as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename="{os.path.basename(attachment_path)}"')
msg.attach(part)
return {'raw': base64.urlsafe_b64encode(msg.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 successfully.')
except HttpError as error:
print(f'An error occurred: {error}')
# 获取凭据
credentials = get_credentials()
# 创建Gmail API服务
service = build('gmail', 'v1', credentials=credentials)
# 创建邮件消息
message = create_message(sender, receiver, subject, message, attachment_path)
# 发送邮件
send_message(service, 'me', message)
该代码示例使用了Google提供的google-auth
和google-auth-oauthlib
库进行OAuth2身份验证,并使用googleapiclient
库建立与Gmail API的连接。在使用代码之前,需要将您自己的电子邮件地址、收件人地址、主题和消息内容替换为适当的值,并将附件路径指定为可选的附件文件路径。
该示例代码将邮件发送给收件人地址,并在成功发送后打印出相应的消息。如果发送过程中发生错误,将打印出相应的错误消息。
建议的腾讯云相关产品和产品介绍链接地址:
请注意,以上产品和链接仅为示例,您可以根据实际需求选择合适的腾讯云产品。
领取专属 10元无门槛券
手把手带您无忧上云