Gmail working
This commit is contained in:
58
src/lib/google.ts
Normal file
58
src/lib/google.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { google } from 'googleapis';
|
||||
import { env } from '$env/dynamic/private';
|
||||
|
||||
const {
|
||||
GOOGLE_CLIENT_ID,
|
||||
GOOGLE_CLIENT_SECRET
|
||||
} = env;
|
||||
|
||||
/* NEW REDIRECT — must match Google Cloud OAuth settings */
|
||||
const REDIRECT_URI = 'http://localhost:5173/private/api/gmail';
|
||||
|
||||
export const scopes = ['https://www.googleapis.com/auth/gmail.send'];
|
||||
|
||||
export function getOAuthClient() {
|
||||
return new google.auth.OAuth2(
|
||||
GOOGLE_CLIENT_ID,
|
||||
GOOGLE_CLIENT_SECRET,
|
||||
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 }
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user