Build Email Features in Lovable with SMASHSEND

Copy and paste these prompts to quickly integrate transactional emails, contact management, and email analytics into your Lovable projects.

Lovable is the AI-powered platform that lets you build web applications using natural language. With these ready-to-use prompts, you can integrate SMASHSEND's powerful email infrastructure into your Lovable projects in minutes.

Each prompt below includes complete code examples and implementation details. Simply copy the prompt, paste it into Lovable, and let AI handle the integration.

Integration Prompts

Initial Setup

Use this prompt to set up SMASHSEND SDK in your Lovable project. You'll need your API key from the SMASHSEND dashboard.

I need to set up SMASHSEND email integration in my Lovable app. Please:

1. Install the @smashsend/node package
2. Create an environment variable for SMASHSEND_API_KEY
3. Set up a utility file at lib/smashsend.ts with the following code:

import { SmashSend } from '@smashsend/node';

if (!process.env.SMASHSEND_API_KEY) {
  throw new Error('Missing SMASHSEND_API_KEY environment variable');
}

export const smashsend = new SmashSend(process.env.SMASHSEND_API_KEY);

Make sure to handle errors properly and provide TypeScript types for all functions.

Create Contact Form

Use this prompt to create a contact form that saves new contacts to SMASHSEND. The form will handle validation, error states, and success feedback.

I need to create a contact form that saves contacts to SMASHSEND. Here's what I need:

1. Create a contact form component with fields for email, firstName, lastName, and any custom properties
2. Create an API route at app/api/contacts/route.ts with this implementation:

import { smashsend } from '@/lib/smashsend';
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  try {
    const body = await request.json();
    
    const contact = await smashsend.contacts.create({
      email: body.email,
      firstName: body.firstName,
      lastName: body.lastName,
      status: 'SUBSCRIBED',
      customProperties: {
        // Add any custom properties here
        source: 'website',
        ...body.customProperties
      }
    });
    
    return NextResponse.json({ success: true, contactId: contact.id });
  } catch (error) {
    console.error('Error creating contact:', error);
    return NextResponse.json(
      { error: 'Failed to create contact' },
      { status: 500 }
    );
  }
}

3. Handle form submission with proper error handling and success feedback
4. Include validation for email format and required fields

Send Transactional Emails

Use this prompt to implement email sending functionality in your Lovable app. Perfect for welcome emails, notifications, and password resets.

I need to send transactional emails using SMASHSEND. Please:

1. Create an API route at app/api/send-email/route.ts:

import { smashsend } from '@/lib/smashsend';
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  try {
    const { to, subject, html, text, from } = await request.json();
    
    const email = await smashsend.emails.send({
      from: from || 'noreply@yourdomain.com',
      to,
      subject,
      html,
      text: text || subject, // Fallback to subject if no text provided
      // Optional: Add tags for analytics
      tags: ['transactional', 'api']
    });
    
    return NextResponse.json({ 
      success: true, 
      emailId: email.id,
      messageId: email.messageId 
    });
  } catch (error) {
    console.error('Error sending email:', error);
    return NextResponse.json(
      { error: 'Failed to send email' },
      { status: 500 }
    );
  }
}

2. Create a function to call this API from the frontend:

export async function sendEmail(data: {
  to: string;
  subject: string;
  html: string;
  text?: string;
  from?: string;
}) {
  const response = await fetch('/api/send-email', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  
  if (!response.ok) {
    throw new Error('Failed to send email');
  }
  
  return response.json();
}

3. Include proper error handling and loading states in the UI

React Email Templates

Use this prompt to create beautiful, responsive email templates using React Email components. Perfect for maintaining consistent branding across all your emails.

I need to send beautifully designed emails using React Email components with SMASHSEND:

1. Install React Email dependencies:
   - @react-email/components
   - @react-email/render

2. Create an email template at components/emails/WelcomeEmail.tsx:

import {
  Body,
  Container,
  Head,
  Heading,
  Html,
  Link,
  Preview,
  Section,
  Text,
} from '@react-email/components';

interface WelcomeEmailProps {
  firstName: string;
  loginUrl: string;
}

export default function WelcomeEmail({ firstName, loginUrl }: WelcomeEmailProps) {
  return (
    <Html>
      <Head />
      <Preview>Welcome to our platform!</Preview>
      <Body style={main}>
        <Container style={container}>
          <Heading style={h1}>Welcome, {firstName}!</Heading>
          <Text style={text}>
            We're excited to have you on board. Get started by exploring
            your dashboard and setting up your first project.
          </Text>
          <Section style={btnContainer}>
            <Link style={button} href={loginUrl}>
              Go to Dashboard
            </Link>
          </Section>
        </Container>
      </Body>
    </Html>
  );
}

const main = {
  backgroundColor: '#f6f9fc',
  fontFamily: '-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Ubuntu,sans-serif',
};

const container = {
  backgroundColor: '#ffffff',
  margin: '0 auto',
  padding: '20px 0 48px',
  marginBottom: '64px',
};

const h1 = {
  color: '#333',
  fontSize: '24px',
  fontWeight: '600',
  lineHeight: '24px',
  margin: '16px 0',
};

const text = {
  color: '#333',
  fontSize: '16px',
  lineHeight: '24px',
  margin: '16px 0',
};

const btnContainer = {
  textAlign: 'center' as const,
};

const button = {
  backgroundColor: '#5469d4',
  borderRadius: '5px',
  color: '#fff',
  fontSize: '16px',
  fontWeight: '600',
  textDecoration: 'none',
  textAlign: 'center' as const,
  display: 'inline-block',
  padding: '12px 20px',
};

3. Update the API route to use React Email:

import { smashsend } from '@/lib/smashsend';
import { render } from '@react-email/render';
import WelcomeEmail from '@/components/emails/WelcomeEmail';

export async function POST(request: Request) {
  const { to, firstName, loginUrl } = await request.json();
  
  const emailHtml = render(
    WelcomeEmail({ firstName, loginUrl })
  );
  
  const email = await smashsend.emails.send({
    from: 'hello@yourdomain.com',
    to,
    subject: 'Welcome to Our Platform!',
    html: emailHtml,
  });
  
  return NextResponse.json({ success: true, emailId: email.id });
}

Custom Contact Properties

Use this prompt to implement custom contact properties for storing additional information like company details, preferences, or any business-specific data.

I need to manage custom contact properties in SMASHSEND. Please:

1. Create an API route to list and create contact properties at app/api/contact-properties/route.ts:

import { smashsend } from '@/lib/smashsend';
import { NextResponse } from 'next/server';

// GET - List all contact properties
export async function GET() {
  try {
    const properties = await smashsend.contactProperties.list();
    return NextResponse.json(properties);
  } catch (error) {
    console.error('Error fetching properties:', error);
    return NextResponse.json(
      { error: 'Failed to fetch properties' },
      { status: 500 }
    );
  }
}

// POST - Create a new contact property
export async function POST(request: Request) {
  try {
    const body = await request.json();
    
    const property = await smashsend.contactProperties.create({
      displayName: body.displayName,
      apiSlug: body.apiSlug,
      type: body.type, // 'text', 'number', 'date', 'boolean', 'select'
      isRequired: body.isRequired || false,
      // For select type, include options
      options: body.options || []
    });
    
    return NextResponse.json(property);
  } catch (error) {
    console.error('Error creating property:', error);
    return NextResponse.json(
      { error: 'Failed to create property' },
      { status: 500 }
    );
  }
}

2. Create a contact with custom properties:

const contact = await smashsend.contacts.create({
  email: 'user@example.com',
  firstName: 'John',
  lastName: 'Doe',
  // Standard properties
  status: 'SUBSCRIBED',
  countryCode: 'US',
  
  // Custom properties (use the apiSlug as the key)
  customProperties: {
    companyName: 'Acme Corp',
    employeeCount: 50,
    industry: 'technology', // For select type properties
    isVipCustomer: true,
    signupDate: new Date().toISOString()
  }
});

3. Update contact properties:

const updatedContact = await smashsend.contacts.update(contactId, {
  customProperties: {
    employeeCount: 100,
    industry: 'software'
  }
});

4. Search contacts by custom properties:

const contacts = await smashsend.contacts.list({
  filter: {
    customProperties: {
      industry: 'technology',
      isVipCustomer: true
    }
  },
  limit: 50
});

Webhook Integration

Use this prompt to implement webhook handling for real-time email event tracking. Track deliveries, opens, clicks, bounces, and more.

I need to set up SMASHSEND webhooks to track email events. Please:

1. Create a webhook endpoint at app/api/webhooks/smashsend/route.ts:

import { smashsend } from '@/lib/smashsend';
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  try {
    // Get the raw body for signature verification
    const body = await request.text();
    const signature = request.headers.get('X-Smashsend-Signature') || '';
    
    // Verify the webhook signature
    const webhookSecret = process.env.SMASHSEND_WEBHOOK_SECRET!;
    const isValid = smashsend.webhooks.verifySignature(
      body,
      signature,
      webhookSecret
    );
    
    if (!isValid) {
      return NextResponse.json(
        { error: 'Invalid signature' },
        { status: 401 }
      );
    }
    
    // Parse the verified payload
    const event = JSON.parse(body);
    
    // Handle different event types
    switch (event.type) {
      case 'email.sent':
        console.log('Email sent:', event.data.emailId);
        // Update your database, trigger notifications, etc.
        break;
        
      case 'email.delivered':
        console.log('Email delivered:', event.data.emailId);
        break;
        
      case 'email.opened':
        console.log('Email opened:', event.data.emailId);
        // Track engagement metrics
        break;
        
      case 'email.clicked':
        console.log('Link clicked:', event.data.link);
        // Track click-through rates
        break;
        
      case 'email.bounced':
        console.log('Email bounced:', event.data.reason);
        // Handle bounce, maybe update contact status
        break;
        
      case 'email.complained':
        console.log('Spam complaint:', event.data.emailId);
        // Immediately unsubscribe the contact
        break;
        
      default:
        console.log('Unknown event type:', event.type);
    }
    
    // Always return 200 to acknowledge receipt
    return NextResponse.json({ received: true });
    
  } catch (error) {
    console.error('Webhook error:', error);
    return NextResponse.json(
      { error: 'Webhook processing failed' },
      { status: 500 }
    );
  }
}

2. Set up the webhook in SMASHSEND dashboard or via API:

const webhook = await smashsend.webhooks.create({
  url: 'https://yourdomain.com/api/webhooks/smashsend',
  events: [
    'email.sent',
    'email.delivered',
    'email.opened',
    'email.clicked',
    'email.bounced',
    'email.complained'
  ],
  description: 'Production webhook endpoint'
});

console.log('Webhook secret:', webhook.secret);
// Save this secret as SMASHSEND_WEBHOOK_SECRET in your environment variables

3. Make sure to handle webhook events asynchronously to avoid timeouts

Ready to start building? Get your API key and begin integrating SMASHSEND into your Lovable projects.

Start Building with SMASHSEND

Join thousands of developers using SMASHSEND to power their email infrastructure.