本项目可实现 Gmail 推送通知功能,借助 Next.js 框架与 Google API 达成实时邮件通知,为用户带来便捷体验。
使用以下命令创建一个全新的 Next.js 项目:
npx create-next-app next-door && cd next-door
在项目根目录下运行以下命令以安装必要的依赖项:
npm install nextjs googleapis @google-cloud/pubsub express cors dotenv
创建一个 .env 文件,并添加以下内容(将占位符替换为实际值):
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_PUBSUB_PROJECT_ID=your_project_id
GOOGLE_PUBSUB_TOPIC_NAME=your_topic_name
GOOGLE_PUBSUB_VERIFICATION_TOKEN=your_verification_token
修改 next.config.js 文件,以确保环境变量在生产环境中可用:
/** @type {import('next').NextConfig} */
const nextConfig = {
env: {
GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
GOOGLE_PUBSUB_PROJECT_ID: process.env.GOOGLE_PUBSUB_PROJECT_ID,
GOOGLE_PUBSUB_TOPIC_NAME: process.env.GOOGLE_PUBSUB_TOPIC_NAME,
GOOGLE_PUBSUB_VERIFICATION_TOKEN: process.env.GOOGLE_PUBSUB_VERIFICATION_TOKEN
}
};
module.exports = nextConfig;
在 Google Cloud Console 中,导航到 PubSub API 并创建一个新的主题。例如,您可以命名为 inbox-zero-updates。
接下来,创建一个订阅以接收来自该主题的通知。您可以在开发环境中使用 ngrok 来处理回拨 URL:
ngrok http --domain=your-domain.ngrok-free.app 3000
然后,在 PubSub 控制台中,为您的订阅配置以下属性:
https://your-domain.ngrok-free.app/api/google/webhook?token=TOKEN.env 文件中设置的 GOOGLE_PUBSUB_VERIFICATION_TOKENHTTP在您的 Next.js 应用中,创建一个 API 路由来处理 Google 的推送通知:
import type { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req, res) {
if (req.method !== 'POST') {
res.status(405).json({ message: 'Method not allowed' });
return;
}
// 验证令牌并处理推送通知
const verificationToken = req.query.token;
if (!verificationToken || verificationToken !== process.env.GOOGLE_PUBSUB_VERIFICATION_TOKEN) {
res.status(401).json({ message: 'Unauthorized' });
return;
}
// 处理实际的推送数据
const data = JSON.parse(req.body);
console.log('Received email notification:', data);
res.json({ message: 'Notification processed successfully' });
}
为了确保您的应用能够实时接收电子邮件通知,您需要定期检查 Gmail API 的更改。为此,您可以设置一个cron作业,每隔一段时间(例如每5分钟)调用一次 /api/google/watch/all 端点。
在项目根目录下创建一个 crons.json 文件,并添加以下内容:
{
"crons": [
{
"path": "/api/google/watch/all",
"schedule": "0 */5 * * *"
}
]
}
使用 Upstash 来运行 cron 作业,您可以按照 Upstash 文档 进行配置。
// pages/_app.tsx
import { NextApp } from 'next/app';
import type { AppProps } from 'next/app';
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<NextApp>
<Component {...pageProps} />
NextApp>
);
}
// pages/index.tsx
import { useState, useEffect } from 'react';
export default function Home() {
const [emailNotifications, setEmailNotifications] = useState([]);
useEffect(() => {
// 定期检查 Gmail API 的更改
const interval = setInterval(() => {
fetch('/api/google/watch/all')
.then((response) => response.json())
.then((data) => setEmailNotifications(data))
.catch((error) => console.error('Error:', error));
}, 5000);
return () => clearInterval(interval);
}, []);
return (
<div>
<h1>实时电子邮件通知h1>
<ul>
{emailNotifications.map((notification, index) => (
<li key={index} >{notification.subject}li>
))}
ul>
div>
);
}
// api/google/watch/all.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { google } from 'googleapis';
export default function handler(req, res) {
const oauth2Client = new google.auth.OAuth2({
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET
});
}