Learn how to build email automation with Lovable: step-by-step setup, templates, segmentation and analytics to boost engagement and save time.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Build an email automation by adding a server API route that calls a transactional email API (e.g., SendGrid), store the API key in Lovable Cloud Secrets, add a small UI trigger or scheduled job file, and test with Lovable Preview — all done via Chat Mode edits, Preview, and Publish (no terminal needed). I’ll give exact Lovable prompts you can paste into Chat Mode to create the files, wire the secret, and verify in Preview. If your project runtime is not Next.js/Pages API, I’ll note the safe fallback (export to GitHub for terminal work).
Create a backend API endpoint in your app that sends emails through SendGrid, a small UI to trigger emails, and wire the SENDGRID_API_KEY via Lovable Cloud Secrets. Use Chat Mode to create/modify files, Preview to test, and Publish to deploy.
Prompt 1 — Create server API route to send email
// Goal: Add a backend API endpoint that sends email via SendGrid
// Files to create: src/pages/api/send-email.ts
// Done when: file exists and returns JSON { ok: true } on success
// Create file src/pages/api/send-email.ts with this content:
import type { NextApiRequest, NextApiResponse } from 'next'
// // Use environment variable SENDGRID_API_KEY from Lovable Secrets
const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })
const { to, subject, text } = req.body
if (!to || !subject || !text) return res.status(400).json({ error: 'Missing fields' })
if (!SENDGRID_API_KEY) return res.status(500).json({ error: 'Missing SENDGRID_API_KEY' })
try {
// // Call SendGrid web API
const resp = await fetch('https://api.sendgrid.com/v3/mail/send', {
method: 'POST',
headers: {
'Authorization': `Bearer ${SENDGRID_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
personalizations: [{ to: [{ email: to }] }],
from: { email: '[email protected]', name: 'Your App' },
subject,
content: [{ type: 'text/plain', value: text }]
})
})
if (!resp.ok) {
const body = await resp.text()
return res.status(502).json({ error: 'SendGrid error', body })
}
return res.status(200).json({ ok: true })
} catch (err) {
return res.status(500).json({ error: 'Unexpected error', message: String(err) })
}
}
Prompt 2 — Add a simple front-end trigger form
// Goal: Add a UI to trigger the email endpoint
// Files to create/modify: src/components/EmailForm.tsx and update src/pages/index.tsx to include it
// Done when: index page shows a form, submitting calls /api/send-email and shows success/failure
// Create src/components/EmailForm.tsx with:
import React, { useState } from 'react'
export default function EmailForm() {
const [to, setTo] = useState('')
const [subject, setSubject] = useState('Test email from Lovable')
const [text, setText] = useState('Hello from Lovable Preview!')
const [status, setStatus] = useState('')
async function sendEmail(e: React.FormEvent) {
e.preventDefault()
setStatus('sending')
const resp = await fetch('/api/send-email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ to, subject, text })
})
const body = await resp.json()
setStatus(resp.ok ? 'sent' : `error: ${body.error || JSON.stringify(body)}`)
}
return (
<form onSubmit={sendEmail}>
<label>To <input value={to} onChange={e => setTo(e.target.value)} /></label>
<label>Subject <input value={subject} onChange={e => setSubject(e.target.value)} /></label>
<label>Text <textarea value={text} onChange={e => setText(e.target.value)} /></label>
<button type="submit">Send</button>
<div>{status}</div>
</form>
)
}
// Update src/pages/index.tsx to import and render <EmailForm />
Prompt 3 — Secrets and integration setup
// Goal: Store SendGrid API key securely in Lovable Cloud
// Steps to do in Lovable UI (not a file change)
// Done when: Environment variable SENDGRID_API_KEY appears in Preview env and API route sees it
// Instructions to paste into Lovable chat so the user follows them:
Please open the Lovable Cloud Secrets UI, create a new secret named SENDGRID_API_KEY, paste your SendGrid API Key value, and save. Do NOT commit the key to code. After saving, Preview will have that env var available to the API route.
This prompt helps an AI assistant understand your setup and guide to build the feature
This prompt helps an AI assistant understand your setup and guide to build the feature
This prompt helps an AI assistant understand your setup and guide to build the feature

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
The best practice: build the AI-driven email automation as a small, testable server endpoint (a Lovable server function) that separates three responsibilities — generate (AI), render (templates), send (email provider) — and use Lovable-native tools: Secrets UI for API keys, Preview + a dry-run flag to validate output without sending, Chat Mode edits for iterative code changes, and Publish/GitHub sync only when tests pass. Keep secrets in Lovable, use idempotency and retry-safe design, validate recipients & consent, and mock/send only through a sandboxed provider during testing.
Keep responsibilities separate: AI generation (subject/body/snippets), templating (merge tokens into HTML), and sending (SendGrid/SES/Postmark). This makes testing and dry-run safe in Lovable.
Working Node.js serverless function — put this in your Lovable server functions folder. It uses OpenAI to draft and SendGrid to send. Use Preview/dry-run before true sends.
// Serverless endpoint: expects OPENAI_API_KEY & SENDGRID_API_KEY in Lovable Secrets
export default async function handler(req, res) {
const {recipient, name, dryRun} = req.body;
// basic validation
if (!recipient) return res.status(400).json({error: 'recipient required'});
// 1) generate email with OpenAI
const openaiResp = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
},
body: JSON.stringify({
model: 'gpt-4o-mini', // choose model available to your account
messages: [
{role: 'system', content: 'You are a concise professional email writer.'},
{role: 'user', content: `Write a short, friendly follow-up email to ${name}. Keep it <= 3 short paragraphs.`}
],
max_tokens: 400
})
});
const openaiData = await openaiResp.json();
const bodyHtml = openaiData.choices?.[0].message?.content || 'Hello';
// 2) if dryRun, return rendered HTML so Lovable Preview can show it
if (dryRun) return res.status(200).json({preview: bodyHtml});
// 3) send via SendGrid
await fetch('https://api.sendgrid.com/v3/mail/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.SENDGRID_API_KEY}`
},
body: JSON.stringify({
personalizations: [{to: [{email: recipient}], subject: 'Quick follow-up'}],
from: {email: '[email protected]', name: 'Your App'},
content: [{type: 'text/html', value: bodyHtml}]
})
});
return res.status(200).json({ok: true});
}
Keep it incremental: iterate prompts and templates inside Chat Mode, use Preview for safety, store keys in Secrets, and publish only when dry-runs and tests pass. This prevents most “works locally but breaks in cloud” surprises in Lovable.
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.