Files
scan-wave/src/lib/google.ts
2025-06-24 14:05:54 +02:00

81 lines
2.0 KiB
TypeScript

import { google } from 'googleapis';
import { env } from '$env/dynamic/private';
export const scopes = ['https://www.googleapis.com/auth/gmail.send'];
export function getOAuthClient() {
return new google.auth.OAuth2(
env.GOOGLE_CLIENT_ID,
env.GOOGLE_CLIENT_SECRET,
env.GOOGLE_REDIRECT_URI
);
}
export function createAuthUrl() {
return getOAuthClient().generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope: scopes
});
}
export async function exchangeCodeForTokens(code: string) {
const { tokens } = await getOAuthClient().getToken(code);
if (!tokens.refresh_token) throw new Error('No refresh_token returned');
return tokens.refresh_token;
}
export async function sendGmail(
refreshToken: string,
{ to, subject, text }: { to: string; subject: string; text: string }
) {
const oauth = getOAuthClient();
oauth.setCredentials({ refresh_token: refreshToken });
const gmail = google.gmail({ version: 'v1', auth: oauth });
const wrappedHtml = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${subject}</title>
<link href="https://fonts.googleapis.com/css?family=Lato:400,700&display=swap" rel="stylesheet">
<style>
body { font-family: 'Lato', Arial, sans-serif; margin: 0; padding: 0; background: #f9f9f9; }
.container {
max-width: 480px;
margin: 0 auto;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
padding: 24px 16px;
word-break: break-word;
}
@media (max-width: 600px) {
.container { padding: 16px 4px; }
}
</style>
</head>
<body>
<div class="container">${text}</div>
</body>
</html>`;
const message = [
`To: ${to}`,
'Content-Type: text/html; charset="UTF-8"',
'Content-Transfer-Encoding: 7bit',
`Subject: ${subject}`,
'',
wrappedHtml
].join('\n');
const raw = Buffer.from(message).toString('base64url');
await gmail.users.messages.send({
userId: 'me',
requestBody: { raw }
});
}