ตัวอย่างโค้ดส่งอีเมล React ใน 2025

ส่งอีเมลแอปเว็บ React พร้อมด้วยเทมเพลต HTML, CSS และ JSX ตัวอย่าง และการรวมเข้ากับการผลิต SMTP

การติดตั้งและข้อกำหนด

คุณจะต้องติดตั้งการอ้างอิง npm ของ @react-email/render และ nodemailer:

npm install @react-email/render nodemailer

รหัสต้นฉบับและตัวอย่าง

สร้างเทมเพลตอีเมลของคุณด้วยไฟล์ .jsx หรือ .js:

// email.jsx
import * as React from 'react';
import { Html } from '@react-email/html';
import { Button } from '@react-email/button';

export function Email(props) {
  const { url } = props;

  return (
    <Html lang="en">
      <Button href={url}>Visit our website</Button>
    </Html>
  );
}

ในตัวอย่างนี้ เราใช้ไลบรารี โหนดเมเลอร์ และผู้สนับสนุนอย่างเป็นทางการ ส่งต่ออีเมล์ เพื่อส่งและดูตัวอย่างอีเมลขาออก

คุณจะต้อง สร้างรหัสผ่าน เพื่อส่งอีเมลขาออก – โปรดปฏิบัติตาม ส่งอีเมลด้วยคู่มือ SMTP โดเมนที่กำหนดเอง ของเรา

// app.js
import { render } from '@react-email/render';
import nodemailer from 'nodemailer';
import { Email } from './email';

const transporter = nodemailer.createTransport({
  host: 'smtp.forwardemail.net',
  port: 465,
  secure: true,
  auth: {
    // TODO: replace `user` and `pass` values from:
    // <https://forwardemail.net/guides/send-email-with-custom-domain-smtp>
    user: 'you@example.com',
    pass: '****************************'
  },
});

const html = render(Email({ url: "https://example.com" }));

const options = {
  from: 'you@example.com',
  to: 'user@gmail.com',
  subject: 'hello world',
  html
};

transporter.sendMail(options);

เรียกใช้แอปเพื่อส่งอีเมล:

node app

ตอนนี้คุณสามารถไปที่ บัญชีของฉัน → อีเมล เพื่อดูสถานะการจัดส่งอีเมลแบบเรียลไทม์ บันทึกการจัดส่งอีเมล และการแสดงตัวอย่าง HTML/ข้อความธรรมดา/ไฟล์แนบ

P.S. 🎉 คุณยังสามารถ ดูตัวอย่างอีเมลในเบราว์เซอร์และ iOS Simulator และ สร้างเทมเพลตอีเมลด้วย Node.js ได้ด้วย