Skip to content

Instantly share code, notes, and snippets.

@hotchpotch
Last active Dec 22, 2020
Embed
What would you like to do?
メールを送るよ
import fetch from "node-fetch"
import { config } from "firebase-functions"
import { createTransport } from "nodemailer"
type GMailOAuth2Config = {
user: string
"client-id": string
"client-secret": string
"refresh-token": string
}
const gmailOAuth2Config = config().gmail as GMailOAuth2Config
const recaptchaV3secret = config().recaptcha.v3secret
async function isValidRecaptchaV3({
secret,
response,
}: {
secret: string
response: string
}): Promise<boolean> {
if (!response || !secret) {
return false
}
try {
const res = await fetch(`https://www.google.com/recaptcha/api/siteverify`, {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
},
body: `secret=${secret}&response=${response}`,
})
const json = await res.json()
return !!json.success
} catch {
return false
}
}
export const sendContactMail = async ({
data,
}: {
data: { recapchaToken: string; body: string }
}) => {
if (
await isValidRecaptchaV3({
secret: recaptchaV3secret,
response: data.recapchaToken,
})
) {
const transport = createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
type: "OAuth2",
user: gmailOAuth2Config.user,
clientId: gmailOAuth2Config["client-id"],
clientSecret: gmailOAuth2Config["client-secret"],
refreshToken: gmailOAuth2Config["refresh-token"],
},
})
try {
await transport.sendMail({
to: gmailOAuth2Config.user,
subject: "おたよりフォームからのおたより",
text: data.body,
})
} catch {
throw "sendmail failed"
}
} else {
throw "recaptcha invalid"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment