import { google } from 'googleapis'; import quotedPrintable from 'quoted-printable'; import { getOAuthClient } from '../auth/server.js'; /** * Create an HTML email template with ScanWave branding * @param text - Email body text * @returns HTML email template */ export function createEmailTemplate(text: string): string { return `

${text}

QR Code

This email has been generated with the help of ScanWave

`; } /** * Send an email through Gmail with QR code * @param refreshToken - Google refresh token * @param params - Email parameters (to, subject, text, qr_code) */ export async function sendGmail( refreshToken: string, { to, subject, text, qr_code }: { to: string; subject: string; text: string; qr_code: string } ) { const oauth = getOAuthClient(); oauth.setCredentials({ refresh_token: refreshToken }); const gmail = google.gmail({ version: 'v1', auth: oauth }); const message_html = createEmailTemplate(text); const boundary = 'BOUNDARY'; const nl = '\r\n'; // RFC-5322 line ending // Convert HTML to a Buffer, then to latin1 string for quotedPrintable.encode const htmlBuffer = Buffer.from(message_html, 'utf8'); const htmlLatin1 = htmlBuffer.toString('latin1'); const htmlQP = quotedPrintable.encode(htmlLatin1); const qrLines = qr_code.replace(/.{1,76}/g, '$&' + nl); const rawParts = [ 'MIME-Version: 1.0', `To: ${to}`, `Subject: ${subject}`, `Content-Type: multipart/related; boundary="${boundary}"`, '', `--${boundary}`, 'Content-Type: text/html; charset="UTF-8"', 'Content-Transfer-Encoding: quoted-printable', '', htmlQP, '', `--${boundary}`, 'Content-Type: image/png', 'Content-Transfer-Encoding: base64', 'Content-ID: ', 'Content-Disposition: inline; filename="qr.png"', '', qrLines, '', `--${boundary}--`, '' ]; const rawMessage = rawParts.join(nl); const raw = Buffer.from(rawMessage).toString('base64url'); await gmail.users.messages.send({ userId: 'me', requestBody: { raw } }); }