Skip to content

Instantly share code, notes, and snippets.

@hotchpotch
Last active December 22, 2020 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hotchpotch/4eaec5982be1466c3932e07d3bbcae02 to your computer and use it in GitHub Desktop.
Save hotchpotch/4eaec5982be1466c3932e07d3bbcae02 to your computer and use it in GitHub Desktop.
メールを送るよ
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