
Contact 페이지의 이메일 전송 폼을 모두 구현한 뒤 서버 구현 없이 이메일을 전송할 수 있는 방법 찾아보던 중, emailjs를 이용한 방법과 구글 스프레드 시트를 이용한 방법이 있다는 것을 알게 되었다.
두 방법을 모두 살펴보니 emailjs가 구현하기 쉬워 보여서(공식문서가 잘 되어 있다) emailjs를 이용하기로 했다.
emailjs
Send email directly from your code | EmailJS
No server side code required. Add static or dynamic attachments, dynamic parameters, captcha code and more. Start with our free tier!
www.emailjs.com
위 사이트에 접속해서 회원가입 후, Email Service 탭 > Add New Service를 선택하고 Gmail을 추가해 메일을 받을 구글 아이디와 연동을 시켰다.
Email Template 탭으로 가면 수신 이메일 양식을 수정할 수 있다.

여기서 사용되는 name, email, message 변수는 내가 코드의 form에서 사용할 input name 값과 동일해야 한다.
추가로 phone_number 등등 다양한 변수를 이용할 수도 있다.
여기까지 마무리 한 뒤 이제 리액트 코드를 작성한다.
emailjs 리액트
emailjs sdk 설치 (https://www.emailjs.com/docs/sdk/installation/)
npm install @emailjs/browser --save
emailjs 리액트 코드( https://www.emailjs.com/docs/examples/reactjs/ )
import React, { useRef } from 'react'; import emailjs from '@emailjs/browser'; export const ContactUs = () => { const form = useRef(); const sendEmail = (e) => { e.preventDefault(); emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', form.current, 'YOUR_PUBLIC_KEY') .then((result) => { console.log(result.text); }, (error) => { console.log(error.text); }); }; return ( <form ref={form} onSubmit={sendEmail}> <label>Name</label> <input type="text" name="user_name" /> <label>Email</label> <input type="email" name="user_email" /> <label>Message</label> <textarea name="message" /> <input type="submit" value="Send" /> </form> ); };
sdk 설치 후 공식문서의 코드를 그대로 프로젝트에 반영하면 된다.
sendForm으로 전송할 Key들의 위치는 아래와 같다.
Service Id

Template Id

Public Id

내가 작성한 최종 코드이다.
contact.js
import { useRef } from "react"; import emailjs from "@emailjs/browser"; import Card from "../components/Card"; import "./Contact.css"; const Contact = () => { const form = useRef(); const sendEmailHandler = (e) => { e.preventDefault(); emailjs .sendForm( process.env.REACT_APP_EMAILJS_SERVICE_ID, process.env.REACT_APP_EMAILJS_TEMPLATE_ID, form.current, process.env.REACT_APP_EMAILJS_PUBLIC_KEY ) .then( function (response) { console.log("SUCCESS!", response.status, response.message); alert( "이메일 전송이 완료되었습니다! 빠른 시일 내에 답장 드리겠습니다." ); form.current.name.value = ""; form.current.email.value = ""; form.current.message.value = ""; }, function (error) { console.log("FAILED...", error); } ); }; return ( <div className="contact"> <h1 className="contact-title"> <a name="Contact">Contact</a> </h1> <p> <a href="mailto:seaofiandme35@gmail.com" className="email-link"> 📧 seaofiandme35@gmail.com </a> </p> <div className="contact-card-wrapper"> <Card className="contact-card"> <form className="contents" ref={form} onSubmit={sendEmailHandler}> <h3>Name</h3> <input type="text" name="name" /> <h3>Email</h3> <input type="email" name="email" /> <h3>Message</h3> <textarea name="message" /> <div className="send-btn"> <button type="submit">Send</button> </div> </form> </Card> </div> </div> ); }; export default Contact;
결과

