Using Email — Agentuity Documentation

Using Email

Send emails and manage addresses with ctx.email

Send outbound emails and manage email addresses under the @agentuity.email domain. The email service is available via ctx.email in agents and c.var.email in routes.

For concepts, inbound processing patterns, and webhook setup, see Email.

send(params)

Send an outbound email. Emails are sent asynchronously; the initial status is always 'pending'.

ParamTypeRequiredDescription
paramsEmailSendParamsyesEmail composition parameters (see below)

EmailSendParams fields:

FieldTypeRequiredDescription
fromstringyesSender address (must be owned by your organization)
tostring[]yesRecipient email addresses
subjectstringyesEmail subject line
textstringnoPlain text body
htmlstringnoHTML body
attachmentsEmailAttachment[]noFile attachments (base64-encoded, max 25 MB total)
headersRecord<string, string>noCustom headers (e.g., In-Reply-To, References for threading)

EmailAttachment fields:

FieldTypeRequiredDescription
filenamestringyesAttachment filename
contentstringyesBase64-encoded file content
contentTypestringnoMIME type (e.g., 'application/pdf')

Returns: Promise<EmailOutbound>

interface EmailOutbound {
  id: string;            // Unique ID (prefixed with eout_)
  from: string;          // Sender address
  to: string;            // Recipient addresses (comma-separated)
  subject?: string;      // Subject line
  text?: string;         // Plain text body
  html?: string;         // HTML body
  status?: string;       // 'pending', 'success', or 'failed'
  error?: string;        // Error message if delivery failed
  created_at?: string;   // ISO 8601 timestamp
}

Example

import { createAgent } from '@agentuity/runtime';
import { z } from 'zod';
 
const agent = createAgent('Notifier', {
  schema: {
    input: z.object({ userEmail: z.string(), name: z.string() }),
    output: z.object({ emailId: z.string() }),
  },
  handler: async (ctx, input) => {
    const result = await ctx.email.send({
      from: 'notifications@agentuity.email',
      to: [input.userEmail],
      subject: `Welcome, ${input.name}!`,
      text: `Hi ${input.name}, thanks for signing up.`,
      html: `<h1>Welcome!</h1><p>Hi ${input.name}, thanks for signing up.</p>`,
    });
 
    ctx.logger.info('Email %s sent, status: %s', result.id, result.status);
    return { emailId: result.id };
  },
});

Example with attachments

const report = await generatePdfReport();
 
await ctx.email.send({
  from: 'reports@agentuity.email',
  to: ['team@example.com'],
  subject: 'Monthly Report',
  text: 'Please find the monthly report attached.',
  attachments: [
    {
      filename: 'report.pdf',
      content: Buffer.from(report).toString('base64'),
      contentType: 'application/pdf',
    },
  ],
});

Address Management

createAddress(localPart)

Create a new email address under the @agentuity.email domain.

ParamTypeRequiredDescription
localPartstringyesThe part before @ (e.g., 'support' creates support@agentuity.email)

Returns: Promise<EmailAddress>

interface EmailAddress {
  id: string;               // Unique ID (prefixed with eaddr_)
  email: string;            // Full email address
  created_at: string;       // ISO 8601 timestamp
  inbound_count?: number;   // Total inbound emails received
  outbound_count?: number;  // Total outbound emails sent
  last_activity?: string;   // ISO 8601 timestamp of last activity
}

Example

const addr = await ctx.email.createAddress('support');
ctx.logger.info('Created: %s', addr.email);
// support@agentuity.email

listAddresses()

List all email addresses owned by the organization.

Returns: Promise<EmailAddress[]>

getAddress(id)

Get an email address by its ID.

ParamTypeRequiredDescription
idstringyesEmail address ID (prefixed with eaddr_)

Returns: Promise<EmailAddress | null>

deleteAddress(id)

Delete an email address.

Returns: Promise<void>

getConnectionConfig(id)

Get IMAP and POP3 connection settings for an email address. Useful for connecting external mail clients.

Returns: Promise<EmailConnectionConfig | null>

interface EmailConnectionConfig {
  email: string;
  imap: { host: string; port: number; tls: string; username: string; password: string };
  pop3: { host: string; port: number; tls: string; username: string; password: string };
}

Destinations

Destinations configure where inbound emails are forwarded when received at an address.

createDestination(addressId, type, config)

Create a forwarding destination for an email address.

ParamTypeRequiredDescription
addressIdstringyesEmail address ID
typestringyesDestination type (e.g., 'url')
configRecord<string, unknown>yesType-specific configuration

Returns: Promise<EmailDestination>

Example

const dest = await ctx.email.createDestination('eaddr_abc123', 'url', {
  url: 'https://example.com/incoming-email',
  headers: { 'Authorization': 'Bearer token' },
});
 
ctx.logger.info('Destination created: %s', dest.id);

For webhook handling patterns, see Webhooks.

listDestinations(addressId)

List all destinations for an email address. Returns: Promise<EmailDestination[]>

deleteDestination(addressId, destinationId)

Remove a destination. Returns: Promise<void>

Inbound Email

listInbound(addressId?)

List received emails, optionally filtered by address ID.

Returns: Promise<EmailInbound[]>

interface EmailInbound {
  id: string;             // Unique ID (prefixed with einb_)
  from: string;           // Sender address
  to: string;             // Recipient address
  subject?: string;       // Subject line
  text?: string;          // Plain text body
  html?: string;          // HTML body
  received_at?: string;   // ISO 8601 timestamp
  headers?: Record<string, unknown>;
  attachments?: EmailStoredAttachment[];
}

Example

const messages = await ctx.email.listInbound('eaddr_abc123');
for (const msg of messages) {
  ctx.logger.info('From: %s, Subject: %s', msg.from, msg.subject);
}

getInbound(id)

Get a specific inbound email. Returns: Promise<EmailInbound | null>

deleteInbound(id)

Delete an inbound email. Returns: Promise<void>

Outbound Email

listOutbound(addressId?)

List sent emails, optionally filtered by address ID.

Returns: Promise<EmailOutbound[]>

getOutbound(id)

Get a specific outbound email. Returns: Promise<EmailOutbound | null>

deleteOutbound(id)

Delete an outbound email record. Returns: Promise<void>

Activity

getActivity(params?)

Get email activity time-series data showing daily inbound and outbound counts.

ParamTypeRequiredDescription
paramsEmailActivityParamsno{ days: number } (min 7, max 365, default 7)

Returns: Promise<EmailActivityResult>

interface EmailActivityResult {
  activity: {
    date: string;      // YYYY-MM-DD
    inbound: number;   // Emails received
    outbound: number;  // Emails sent
  }[];
  days: number;        // Number of days returned
}

Example

const activity = await ctx.email.getActivity({ days: 30 });
for (const point of activity.activity) {
  ctx.logger.info('%s: %d in, %d out', point.date, point.inbound, point.outbound);
}