PhoenixKit.Emails (phoenix_kit v1.5.2)

View Source

Email system for PhoenixKit - main API module.

This module provides the primary interface for email functionality, including system configuration, log management, event management, and analytics.

Core Features

  • Email Logging: Comprehensive logging of all outgoing emails
  • Event Management: Manage delivery, bounce, complaint, open, and click events
  • AWS SES Integration: Deep integration with AWS SES for event management
  • Analytics: Detailed metrics and engagement analysis
  • System Settings: Configurable options for system behavior
  • Rate Limiting: Protection against abuse and spam
  • Archival: Automatic cleanup and archival of old data

System Settings

All settings are stored in the PhoenixKit settings system with module "email_system":

  • email_enabled - Enable/disable the entire system
  • email_save_body - Save full email body (vs preview only)
  • email_save_headers - Save email headers (vs empty map)
  • email_ses_events - Manage AWS SES delivery events
  • email_retention_days - Days to keep emails (default: 90)
  • aws_ses_configuration_set - AWS SES configuration set name
  • email_compress_body - Compress body after N days
  • email_archive_to_s3 - Enable S3 archival
  • email_sampling_rate - Percentage of emails to fully log

Core Functions

System Management

Email Log Management

Event Management

Analytics & Metrics

Maintenance

Usage Examples

# Check if system is enabled
if PhoenixKit.Emails.enabled?() do
  # System is active
end

# Get system statistics
stats = PhoenixKit.Emails.get_system_stats(:last_30_days)
# => %{total_sent: 5000, delivered: 4850, bounce_rate: 2.5, open_rate: 23.4}

# Get campaign performance
campaign_stats = PhoenixKit.Emails.get_campaign_stats("newsletter_2024")
# => %{total_sent: 1000, delivery_rate: 98.5, open_rate: 25.2, click_rate: 4.8}

# Process webhook from AWS SES
{:ok, event} = PhoenixKit.Emails.process_webhook_event(webhook_data)

# Clean up old data
{deleted_count, _} = PhoenixKit.Emails.cleanup_old_logs(90)

Configuration Example

# In your application config
config :phoenix_kit,
  email_enabled: true,
  email_save_body: false,
  email_retention_days: 90,
  aws_ses_configuration_set: "my-app-system"

Summary

Functions

Archives old emais to S3 if archival is enabled.

Checks if AWS credentials are configured.

Removes emails older than the specified number of days.

Compresses body_full field for old emails to save storage.

Counts emails with optional filtering (without loading all records).

Creates an email system event.

Creates an email log if system is enabled.

Deletes an email log.

Disables the email system.

Enables the email system.

Checks if the email system is enabled.

Fetch SES events from DLQ queue for specific message ID.

Fetch SES events from main SQS queue for specific message ID.

Gets AWS access key with Settings DB priority.

Gets the AWS region for SES and SQS services.

Gets AWS secret key with Settings DB priority.

Gets statistics for a specific campaign.

Gets the current email system configuration.

Gets daily delivery trend data for chart visualization.

Gets engagement metrics with trend analysis.

Gets geographic distribution of engagement events.

Gets a single email log by ID.

Gets an email log by message ID.

Gets provider-specific performance metrics.

Gets the configured retention period for emails in days.

Gets the sampling rate for email logging (percentage).

Gets the AWS SES configuration set name.

Gets the AWS SNS Topic ARN for email events.

Gets comprehensive SQS configuration.

Gets the AWS SQS Dead Letter Queue URL.

Gets the maximum number of SQS messages to receive per polling cycle.

Gets the SQS polling interval in milliseconds.

Gets the AWS SQS Queue ARN for email events.

Gets the AWS SQS Queue URL for email events.

Gets the SQS message visibility timeout in seconds.

Gets overall system statistics for a time period.

Gets template-specific performance metrics.

Gets the most clicked links for a time period.

Lists events for a specific email log.

Lists emails with optional filters.

Processes an incoming webhook event (typically from AWS SES).

Checks if full email body saving is enabled.

Checks if email headers saving is enabled.

Checks if AWS SES event management is enabled.

Sets the AWS region for SES and SQS services.

Sets the number of days after which to compress email bodies.

Sets the retention period for emails.

Enables or disables S3 archival for old email data.

Sets the sampling rate for email logging.

Enables or disables full email body saving.

Enables or disables email headers saving.

Sets the AWS SES configuration set name.

Enables or disables AWS SES event management.

Sets the AWS SNS Topic ARN for email events.

Sets the AWS SQS Dead Letter Queue URL.

Sets the maximum number of SQS messages to receive per polling cycle.

Enables or disables SQS polling.

Sets the SQS polling interval in milliseconds.

Sets the AWS SQS Queue ARN for email events.

Sets the AWS SQS Queue URL for email events.

Sets the SQS message visibility timeout in seconds.

Checks if SQS polling is enabled.

Manually sync email status by fetching events from SQS queues.

Updates the status of an email log.

Functions

archive_to_s3(days_old \\ nil)

Archives old emais to S3 if archival is enabled.

Examples

iex> PhoenixKit.Emails.archive_to_s3()
{:ok, archived_count: 100, s3_key: "archives/2024/01/emails.json"}

aws_configured?()

Checks if AWS credentials are configured.

Checks both Settings Database and environment variables (Settings DB takes priority).

Examples

iex> PhoenixKit.Emails.aws_configured?()
true

cleanup_old_logs(days_old \\ nil)

Removes emails older than the specified number of days.

Uses the system retention setting if no days specified.

Examples

iex> PhoenixKit.Emails.cleanup_old_logs()
{150, nil}  # Deleted 150 records

iex> PhoenixKit.Emails.cleanup_old_logs(180)
{75, nil}   # Deleted 75 records older than 180 days

compress_old_bodies(days_old \\ nil)

Compresses body_full field for old emails to save storage.

Examples

iex> PhoenixKit.Emails.compress_old_bodies()
{25, nil}  # Compressed 25 records

iex> PhoenixKit.Emails.compress_old_bodies(60)
{40, nil}  # Compressed 40 records older than 60 days

count_logs(filters \\ %{})

Counts emails with optional filtering (without loading all records).

Parameters

  • filters - Map of filters to apply (optional)

Examples

iex> PhoenixKit.Emails.count_logs(%{status: "bounced"})
42

create_event(attrs \\ %{})

Creates an email system event.

Examples

iex> PhoenixKit.Emails.create_event(%{
  email_log_id: 1,
  event_type: "open"
})
{:ok, %Event{}}

create_log(attrs \\ %{})

Creates an email log if system is enabled.

Examples

iex> PhoenixKit.Emails.create_log(%{
  message_id: "abc123",
  to: "user@example.com",
  from: "app@example.com"
})
{:ok, %Log{}}

delete_log(log)

Deletes an email log.

Examples

iex> log = PhoenixKit.Emails.get_log!(1)
iex> PhoenixKit.Emails.delete_log(log)
{:ok, %Log{}}

disable_system()

Disables the email system.

Sets the "email_enabled" setting to false.

Examples

iex> PhoenixKit.Emails.disable_system()
{:ok, %Setting{}}

enable_system()

Enables the email system.

Sets the "email_enabled" setting to true.

Examples

iex> PhoenixKit.Emails.enable_system()
{:ok, %Setting{}}

enabled?()

Checks if the email system is enabled.

Returns true if the "email_enabled" setting is true.

Examples

iex> PhoenixKit.Emails.enabled?()
true

fetch_dlq_events_for_message(message_id)

Fetch SES events from DLQ queue for specific message ID.

Parameters

  • message_id - The AWS SES message ID to search for

Returns

List of SES events matching the message ID from DLQ.

fetch_sqs_events_for_message(message_id)

Fetch SES events from main SQS queue for specific message ID.

Parameters

  • message_id - The AWS SES message ID to search for

Returns

List of SES events matching the message ID.

get_aws_access_key()

Gets AWS access key with Settings DB priority.

Priority: Settings Database → Environment Variables

Examples

iex> PhoenixKit.Emails.get_aws_access_key()
"AKIA..."

get_aws_region()

Gets the AWS region for SES and SQS services.

Examples

iex> PhoenixKit.Emails.get_aws_region()
"eu-north-1"

get_aws_secret_key()

Gets AWS secret key with Settings DB priority.

Priority: Settings Database → Environment Variables

Examples

iex> PhoenixKit.Emails.get_aws_secret_key()
"secret..."

get_campaign_stats(campaign_id)

Gets statistics for a specific campaign.

Examples

iex> PhoenixKit.Emails.get_campaign_stats("newsletter_2024")
%{
  total_sent: 1000,
  delivery_rate: 98.5,
  open_rate: 25.2,
  click_rate: 4.8
}

get_config()

Gets the current email system configuration.

Returns a map with all current settings.

Examples

iex> PhoenixKit.Emails.get_config()
%{
  enabled: true,
  save_body: false,
  ses_events: true,
  retention_days: 90,
  sampling_rate: 100,
  ses_configuration_set: "my-system",
  sns_topic_arn: "arn:aws:sns:eu-north-1:123456789012:phoenixkit-email-events",
  sqs_queue_url: "https://sqs.eu-north-1.amazonaws.com/123456789012/phoenixkit-email-queue",
  sqs_polling_enabled: false,
  aws_region: "eu-north-1"
}

get_daily_delivery_trends(period \\ :last_7_days)

Gets daily delivery trend data for chart visualization.

Examples

iex> PhoenixKit.Emails.get_daily_delivery_trends(:last_7_days)
%{
  labels: ["2024-09-01", "2024-09-02", ...],
  delivered: [120, 190, 300, ...],
  bounced: [5, 10, 15, ...]
}

get_engagement_metrics(period \\ :last_30_days)

Gets engagement metrics with trend analysis.

Examples

iex> PhoenixKit.Emails.get_engagement_metrics(:last_7_days)
%{
  avg_open_rate: 24.5,
  avg_click_rate: 4.2,
  bounce_rate: 2.8,
  engagement_trend: :increasing
}

get_geo_stats(event_type, period \\ :last_30_days)

Gets geographic distribution of engagement events.

Examples

iex> PhoenixKit.Emails.get_geo_stats("open", :last_30_days)
%{"US" => 500, "CA" => 200, "UK" => 150}

get_log!(id)

Gets a single email log by ID.

Raises Ecto.NoResultsError if the log does not exist or system is disabled.

Examples

iex> PhoenixKit.Emails.get_log!(123)
%Log{}

get_log_by_message_id(message_id)

Gets an email log by message ID.

Examples

iex> PhoenixKit.Emails.get_log_by_message_id("msg-abc123")
%Log{}

get_provider_performance(period \\ :last_7_days)

Gets provider-specific performance metrics.

Examples

iex> PhoenixKit.Emails.get_provider_performance(:last_7_days)
%{
  "aws_ses" => %{delivery_rate: 98.5, bounce_rate: 1.5},
  "smtp" => %{delivery_rate: 95.0, bounce_rate: 5.0}
}

get_retention_days()

Gets the configured retention period for emails in days.

Examples

iex> PhoenixKit.Emails.get_retention_days()
90

get_sampling_rate()

Gets the sampling rate for email logging (percentage).

Examples

iex> PhoenixKit.Emails.get_sampling_rate()
100  # Log 100% of emails

get_ses_configuration_set()

Gets the AWS SES configuration set name.

Examples

iex> PhoenixKit.Emails.get_ses_configuration_set()
"my-app-system"

get_sns_topic_arn()

Gets the AWS SNS Topic ARN for email events.

Examples

iex> PhoenixKit.Emails.get_sns_topic_arn()
"arn:aws:sns:eu-north-1:123456789012:phoenixkit-email-events"

get_sqs_config()

Gets comprehensive SQS configuration.

Examples

iex> PhoenixKit.Emails.get_sqs_config()
%{
  sns_topic_arn: "arn:aws:sns:...",
  queue_url: "https://sqs.eu-north-1.amazonaws.com/...",
  polling_enabled: true,
  polling_interval_ms: 5000,
  max_messages_per_poll: 10
}

get_sqs_dlq_url()

Gets the AWS SQS Dead Letter Queue URL.

Examples

iex> PhoenixKit.Emails.get_sqs_dlq_url()
"https://sqs.eu-north-1.amazonaws.com/123456789012/phoenixkit-email-dlq"

get_sqs_max_messages()

Gets the maximum number of SQS messages to receive per polling cycle.

Examples

iex> PhoenixKit.Emails.get_sqs_max_messages()
10

get_sqs_polling_interval()

Gets the SQS polling interval in milliseconds.

Examples

iex> PhoenixKit.Emails.get_sqs_polling_interval()
5000  # 5 seconds

get_sqs_queue_arn()

Gets the AWS SQS Queue ARN for email events.

Examples

iex> PhoenixKit.Emails.get_sqs_queue_arn()
"arn:aws:sqs:eu-north-1:123456789012:phoenixkit-email-queue"

get_sqs_queue_url()

Gets the AWS SQS Queue URL for email events.

Examples

iex> PhoenixKit.Emails.get_sqs_queue_url()
"https://sqs.eu-north-1.amazonaws.com/123456789012/phoenixkit-email-queue"

get_sqs_visibility_timeout()

Gets the SQS message visibility timeout in seconds.

Examples

iex> PhoenixKit.Emails.get_sqs_visibility_timeout()
300  # 5 minutes

get_system_stats(period \\ :last_30_days)

Gets overall system statistics for a time period.

Examples

iex> PhoenixKit.Emails.get_system_stats(:last_30_days)
%{
  total_sent: 5000,
  delivered: 4850,
  bounced: 150,
  opened: 1200,
  clicked: 240,
  delivery_rate: 97.0,
  bounce_rate: 3.0,
  open_rate: 24.7,
  click_rate: 20.0
}

get_template_stats(period \\ :last_30_days)

Gets template-specific performance metrics.

Examples

iex> PhoenixKit.Emails.get_template_stats(:last_30_days)
%{
  "welcome_email" => %{sent: 100, delivered: 95, opened: 45, clicked: 12},
  "password_reset" => %{sent: 50, delivered: 48, opened: 30, clicked: 8}
}

get_top_links(period \\ :last_30_days, limit \\ 10)

Gets the most clicked links for a time period.

Examples

iex> PhoenixKit.Emails.get_top_links(:last_30_days, 10)
[%{url: "https://example.com/product", clicks: 150}, ...]

list_events_for_log(email_log_id)

Lists events for a specific email log.

Examples

iex> PhoenixKit.Emails.list_events_for_log(123)
[%Event{}, ...]

list_logs(filters \\ %{})

Lists emails with optional filters.

Options

  • :status - Filter by status (sent, delivered, bounced, etc.)
  • :campaign_id - Filter by campaign
  • :template_name - Filter by template
  • :provider - Filter by email provider
  • :from_date - Emails sent after this date
  • :to_date - Emails sent before this date
  • :recipient - Filter by recipient email
  • :limit - Limit results (default: 50)
  • :offset - Offset for pagination

Examples

iex> PhoenixKit.Emails.list_logs(%{status: "bounced", limit: 10})
[%Log{}, ...]

process_webhook_event(webhook_data)

Processes an incoming webhook event (typically from AWS SES).

Examples

iex> webhook_data = %{
  "eventType" => "bounce",
  "mail" => %{"messageId" => "abc123"}
}
iex> PhoenixKit.Emails.process_webhook_event(webhook_data)
{:ok, %Event{}}

save_body_enabled?()

Checks if full email body saving is enabled.

Returns true if the "email_save_body" setting is true.

Examples

iex> PhoenixKit.Emails.save_body_enabled?()
false

save_headers_enabled?()

Checks if email headers saving is enabled.

Returns true if the "email_save_headers" setting is true.

Examples

iex> PhoenixKit.Emails.save_headers_enabled?()
false

ses_events_enabled?()

Checks if AWS SES event management is enabled.

Examples

iex> PhoenixKit.Emails.ses_events_enabled?()
true

set_aws_region(region)

Sets the AWS region for SES and SQS services.

Examples

iex> PhoenixKit.Emails.set_aws_region("eu-north-1")
{:ok, %Setting{}}

set_compress_after_days(days)

Sets the number of days after which to compress email bodies.

Examples

iex> PhoenixKit.Emails.set_compress_after_days(30)
{:ok, %Setting{}}

set_retention_days(days)

Sets the retention period for emails.

Examples

iex> PhoenixKit.Emails.set_retention_days(180)
{:ok, %Setting{}}

set_s3_archival(enabled)

Enables or disables S3 archival for old email data.

Examples

iex> PhoenixKit.Emails.set_s3_archival(true)
{:ok, %Setting{}}

set_sampling_rate(percentage)

Sets the sampling rate for email logging.

Examples

iex> PhoenixKit.Emails.set_sampling_rate(80)  # Log 80% of emails
{:ok, %Setting{}}

set_save_body(enabled)

Enables or disables full email body saving.

Examples

iex> PhoenixKit.Emails.set_save_body(true)
{:ok, %Setting{}}

set_save_headers(enabled)

Enables or disables email headers saving.

Examples

iex> PhoenixKit.Emails.set_save_headers(true)
{:ok, %Setting{}}

set_ses_configuration_set(config_set_name)

Sets the AWS SES configuration set name.

Examples

iex> PhoenixKit.Emails.set_ses_configuration_set("my-system-set")
{:ok, %Setting{}}

set_ses_events(enabled)

Enables or disables AWS SES event management.

Examples

iex> PhoenixKit.Emails.set_ses_events(true)
{:ok, %Setting{}}

set_sns_topic_arn(topic_arn)

Sets the AWS SNS Topic ARN for email events.

Examples

iex> PhoenixKit.Emails.set_sns_topic_arn("arn:aws:sns:eu-north-1:123456789012:phoenixkit-email-events")
{:ok, %Setting{}}

set_sqs_dlq_url(dlq_url)

Sets the AWS SQS Dead Letter Queue URL.

Examples

iex> PhoenixKit.Emails.set_sqs_dlq_url("https://sqs.eu-north-1.amazonaws.com/123456789012/phoenixkit-email-dlq")
{:ok, %Setting{}}

set_sqs_max_messages(max_messages)

Sets the maximum number of SQS messages to receive per polling cycle.

Examples

iex> PhoenixKit.Emails.set_sqs_max_messages(20)
{:ok, %Setting{}}

set_sqs_polling(enabled)

Enables or disables SQS polling.

Examples

iex> PhoenixKit.Emails.set_sqs_polling(true)
{:ok, %Setting{}}

set_sqs_polling_interval(interval_ms)

Sets the SQS polling interval in milliseconds.

Examples

iex> PhoenixKit.Emails.set_sqs_polling_interval(3000)  # 3 seconds
{:ok, %Setting{}}

set_sqs_queue_arn(queue_arn)

Sets the AWS SQS Queue ARN for email events.

Examples

iex> PhoenixKit.Emails.set_sqs_queue_arn("arn:aws:sqs:eu-north-1:123456789012:phoenixkit-email-queue")
{:ok, %Setting{}}

set_sqs_queue_url(queue_url)

Sets the AWS SQS Queue URL for email events.

Examples

iex> PhoenixKit.Emails.set_sqs_queue_url("https://sqs.eu-north-1.amazonaws.com/123456789012/phoenixkit-email-queue")
{:ok, %Setting{}}

set_sqs_visibility_timeout(timeout_seconds)

Sets the SQS message visibility timeout in seconds.

Examples

iex> PhoenixKit.Emails.set_sqs_visibility_timeout(600)  # 10 minutes
{:ok, %Setting{}}

sqs_polling_enabled?()

Checks if SQS polling is enabled.

Examples

iex> PhoenixKit.Emails.sqs_polling_enabled?()
true

sync_email_status(message_id)

Manually sync email status by fetching events from SQS queues.

This function searches for events in both the main SQS queue and DLQ that match the given message_id and processes them to update email status.

Parameters

  • message_id - The AWS SES message ID or internal PhoenixKit message ID to sync

Returns

  • {:ok, result} - Successful sync with processing results
  • {:error, reason} - Error during sync process

Examples

iex> PhoenixKit.Emails.sync_email_status("0110019971abc123-...")
{:ok, %{events_processed: 3, log_updated: true}}

iex> PhoenixKit.Emails.sync_email_status("pk_abc123...")
{:ok, %{events_processed: 1, log_updated: true}}

update_log_status(log, status)

Updates the status of an email log.

Examples

iex> PhoenixKit.Emails.update_log_status(log, "delivered")
{:ok, %Log{}}