【Gmail】Google OAuth2 发送邮件配置(带代码)

本文详细介绍了如何通过GoogleCloud项目和OAuth2授权机制,安全地集成Gmail服务,包括创建项目、添加应用权限、获取授权、发送和收取邮件的过程。
摘要由CSDN通过智能技术生成

背景

gmail将全面禁用账号、密码登陆方式,官方相关文档,对于需要调用gmail相关的服务需要做出相应的调整。这里使用Google Cloud应用的形式来接入Gmail,类似的,也可以通过该方式来调用其他的Google Cloud服务。

创建项目及应用

创建项目

使用链接登陆到Google控制台,通过如下操作创建一个项目
在这里插入图片描述
填入项目名称,并创建项目

在这里插入图片描述
项目创建完成会有相应的通知(贴心)
在这里插入图片描述
切换到刚创建的项目下,开始创建应用
在这里插入图片描述

配置项目应用

点击【API和服务】
在这里插入图片描述
通过如下操作添加gmail
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
应用启用后,添加凭据,如下图所示
在这里插入图片描述
这里根据自己的应用选择
在这里插入图片描述
填入应用信息,这里如果有图标也需要填入,测试时可不使用
在这里插入图片描述
添加应用需要权限,这里如果你只需要发送邮件,则选择如下权限即可
在这里插入图片描述
类似的方式搜索添加如下权限(这里根据需要添加),这些权限在用户授权的时候会展示在用户界面

    "https://www.googleapis.com/auth/userinfo.profile",
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/gmail.send",

添加后的结果如下
在这里插入图片描述
选择自己的应用类型,这里为Web应用,选择如下,然后填入【已获授权的重定向 URI】,该地址是用户授权后,google会调用的地址,
在这里插入图片描述

添加OAuth凭据

应用启用后,添加凭据,如下图所示
在这里插入图片描述
选择应用类型
在这里插入图片描述
完成OAuth客户端创建
在这里插入图片描述
创建完成后,会得到如下内容,该内容会用于运维/开发。
在这里插入图片描述

应用调试

安装依赖

pip install oauth2client
pip install google-auth

获取授权链接

from oauth2client.client import OAuth2WebServerFlow

SCOPES = [
    "https://www.googleapis.com/auth/userinfo.profile",
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/gmail.send",
    "https://www.googleapis.com/auth/calendar",
]

CLIENT_ID = '***' 	# 应用的client_id
CLIENT_SECRET = '***' # 应用的secret
auth_uri = "https://accounts.google.com/o/oauth2/auth"
REDIRECT_URI = "***" # 与控制台的会调url一致

oauth2_flow = OAuth2WebServerFlow(
    CLIENT_ID,
    CLIENT_SECRET,
    SCOPES,
    auth_uri=auth_uri,
)
oauth2_flow.redirect_uri = REDIRECT_URI

# 获取授权连接
auth_url = oauth2_flow.step1_get_authorize_url()

授权链接产生后,需要由用户打开并授权

用户授权回调

回调参数格式

code=4/0AeaYSHAPuZsf6Csifvsssq5vCbvA96ghhhlplL8stG_W5yNr0vkQfRVHJA-YobSyg&scope=email%20profile%20https://www.googleapis.com/auth/gmail.readonly%20https://www.googleapis.com/auth/gmail.send%20https://www.googleapis.com/auth/calendar%20openid%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/userinfo.email&authuser=1&prompt=consent

凭据获取

使用上述参数中的code进行获取(每次授权只能被调用一次)

code = callback_params.get("code")
credentials = oauth2_flow.step2_exchange(code)
credentials.to_json() # 凭据内容

根据凭据获取用户信息

from googleapiclient.discovery import build

user_info = build(
    serviceName='oauth2', version='v2', credentials=credentials
).userinfo().get().execute()

收取邮件

# 收取邮件
from googleapiclient.discovery import build


def list_messages(service, user_id, query=''):
    """List all messages of the user's mailbox matching the query."""
    try:
        response = service.users().messages().list(userId=user_id, q=query).execute()
        messages = []
        if 'messages' in response:
            messages.extend(response['messages'])

        while 'nextPageToken' in response:
            page_token = response['nextPageToken']
            response = service.users().messages().list(
            	userId=user_id, q=query, pageToken=page_token
           	).execute()
            messages.extend(response['messages'])

        return messages
    except Exception as e:
        print('An error occurred: %s' % e)
        return None
    
def get_message(service, user_id, msg_id):
    """Get a specific message."""
    try:
        message = service.users().messages().get(userId=user_id, id=msg_id).execute()
        return message
    except Exception as e:
        print('An error occurred: %s' % e)
        return None

service = build('gmail', 'v1', credentials=credentials)
# 查询条件,参考:https://support.google.com/mail/answer/7190?hl=zh-Hans
messages = list_messages(service, 'me', query='is:unread')
if messages:
    for message in messages:
        msg_id = message['id']
        msg = get_message(service, 'me', msg_id)
        print(msg)

发送邮件

# 发送邮件
import base64
from email.mime.text import MIMEText
from googleapiclient.discovery import build

def create_message(sender, to, subject, message_text):
    """Create a message for an email."""
    message = MIMEText(message_text)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    raw_message = base64.urlsafe_b64encode(message.as_bytes())
    raw_message = raw_message.decode()
    return {'raw': raw_message}

def send_message(service, user_id, message):
    """Send an email message."""
    try:
        message = service.users().messages().send(userId=user_id, body=message).execute()
        print('Message Id: %s' % message['id'])
        return message
    except Exception as e:
        print('An error occurred: %s' % e)
        return None
    
service = build('gmail', 'v1', credentials=credentials)

# 创建邮件消息
sender = '' # 发件人
to = '' # 收件箱
subject = 'Test Email'
message_text = 'This is a test email sent from Gmail API.'
message = create_message(sender, to, subject, message_text)

# 发送邮件
send_message(service, 'me', message)
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的示例代码,可以将OAuth2配置到Spring Boot应用程序中: 首先,需要在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.1.0.RELEASE</version> </dependency> ``` 然后,在Spring Boot应用程序的配置文件中添加以下配置: ```yaml server: port: 8080 spring: security: oauth2: client: registration: google: client-id: <your-client-id> client-secret: <your-client-secret> scope: - email - profile provider: google: authorization-uri: https://accounts.google.com/o/oauth2/auth token-uri: https://accounts.google.com/o/oauth2/token user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo user-name-attribute: sub ``` 在上面的配置中,我们添加了一个名为“google”的OAuth2客户端,并设置了客户端ID和客户端密钥。我们还指定了要请求的Scope(email和profile)以及提供程序的授权URI,令牌URI和用户信息URI。 最后,在我们的Spring Boot应用程序中添加一个OAuth2保护资源: ```java @RestController public class HelloWorldController { @GetMapping("/") @PreAuthorize("hasAuthority('ROLE_USER')") public String helloWorld() { return "Hello World!"; } } ``` 在上面的代码中,我们使用@PreAuthorize注释来确保只有具有ROLE_USER权限的用户才能访问我们的保护资源。 希望这个示例能够帮助你将OAuth2配置到Spring Boot应用程序中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值