51 lines
1.2 KiB
TypeScript
51 lines
1.2 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 raw = Buffer
|
|
.from(
|
|
[`To: ${to}`,
|
|
'Content-Type: text/plain; charset="UTF-8"',
|
|
'Content-Transfer-Encoding: 7bit',
|
|
`Subject: ${subject}`,
|
|
'',
|
|
text].join('\n'))
|
|
.toString('base64url');
|
|
|
|
await gmail.users.messages.send({
|
|
userId: 'me',
|
|
requestBody: { raw }
|
|
});
|
|
}
|