DialFocusサイトの問い合わせフォームの入力内容をGmailアドレスに転送する機能をCloudflare Workers + Email Routingで実装します。
npm install -g wrangler
wrangler login
mkdir tsuchiya-contact-form
cd tsuchiya-contact-form
wrangler init
name = "tsuchiya-contact-form"
main = "src/index.js"
compatibility_date = "2023-12-01"
[env.production]
vars = { ENVIRONMENT = "production" }
[[env.production.bindings]]
name = "EMAIL"
type = "send_email"
wrangler secret put GMAIL_ADDRESS
# プロンプトでGmailアドレスを入力
export default {
async fetch(request, env) {
// CORS設定(実際のPagesドメインに変更)
const corsHeaders = {
'Access-Control-Allow-Origin': 'https://your-pages-domain.pages.dev',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
};
// OPTIONSリクエストの処理(CORS preflight)
if (request.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
// POSTリクエストの処理
if (request.method === 'POST') {
try {
const formData = await request.json();
// バリデーション
if (!formData.email || !formData.subject || !formData.message) {
return new Response(
JSON.stringify({ error: 'Required fields missing' }),
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
// メールアドレスの簡易バリデーション
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(formData.email)) {
return new Response(
JSON.stringify({ error: 'Invalid email format' }),
{ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
// メール送信
await env.EMAIL.send({
from: '[email protected]', // 実際のドメインに変更
to: env.GMAIL_ADDRESS,
subject: `[DialFocus Contact] ${formData.subject}`,
text: `
問い合わせフォームからのメッセージ
差出人: ${formData.email}
件名: ${formData.subject}
メッセージ:
${formData.message}
---
送信日時: ${new Date().toISOString()}
`,
});
return new Response(
JSON.stringify({ success: true, message: 'Email sent successfully' }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
} catch (error) {
console.error('Email sending error:', error);
return new Response(
JSON.stringify({ error: 'Failed to send email' }),
{ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
);
}
}
return new Response('Method not allowed', {
status: 405,
headers: corsHeaders
});
},
};
Email Routing有効化時に自動で設定されます:
Type: MX
Name: @
Content: isaac.mx.cloudflare.net
Priority: 10
[email protected]wrangler deploy
デプロイ完了後、以下のようなURLが発行されます:
https://tsuchiya-contact-form.your-subdomain.workers.dev
既存のフォーム送信処理を以下に置き換え:
// フォーム送信処理の修正(既存のsubmitイベントリスナー内)
if (!hasErrors) {
submitButton.disabled = true;
submitButton.textContent = '送信中...';
try {
// Workers APIに送信
const response = await fetch('https://tsuchiya-contact-form.your-subdomain.workers.dev/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
subject: subject,
message: message,
}),
});
const result = await response.json();
if (response.ok && result.success) {
// 成功処理
form.style.display = 'none';
successMessage.classList.add('show');
// 3秒後にフォームをリセット
setTimeout(() => {
form.reset();
form.style.display = 'block';
successMessage.classList.remove('show');
submitButton.disabled = false;
submitButton.textContent = 'メッセージを送信';
}, 3000);
} else {
throw new Error(result.error || '送信に失敗しました');
}
} catch (error) {
console.error('Form submission error:', error);
alert('送信に失敗しました。もう一度お試しください。');
submitButton.disabled = false;
submitButton.textContent = 'メッセージを送信';
}
}
同様の処理を英語版にも適用:
// 英語版のsubmitButton.textContentを変更
submitButton.textContent = 'Sending...';
// 成功後
submitButton.textContent = 'Send Message';
your-pages-domain.pages.dev → 実際のPagesドメインyour-domain.com → 実際のドメイン名your-subdomain → 実際のWorkersサブドメインCORSのAccess-Control-Allow-Originを正確なPagesドメインに設定
// Workers内でIP別のレート制限を実装
const rateLimitKey = request.headers.get('CF-Connecting-IP');
// KV Storageを使用してレート制限実装
wrangler tail tsuchiya-contact-form
独自ドメインからGmail経由でメール送信を可能にする設定です。フォーム機能には不要ですが、プロフェッショナルな対応のために設定できます。
you@[ドメイン]として自動的に送受信可能名前: あなたの名前
メールアドレス: contact@[ドメイン]
エイリアスとして扱う: チェック
SMTPサーバー: [サービス提供のSMTPサーバー]
ポート: 587 (TLS) または 465 (SSL)
ユーザー名: [SMTP認証ユーザー名]
パスワード: [SMTP認証パスワード]
TLS接続: 有効
contact@[ドメイン]に送信--
Tsuchiya
DialFocus Developer
contact@[ドメイン]
Type: TXT
Name: @
Content: v=spf1 include:[SMTPサービス] ~all
SMTPサービス提供の設定に従って追加
この手順書に従って実装することで、問い合わせフォームからGmailへのメール転送機能が完成します。