PhoenixKit.Emails (phoenix_kit v1.5.2)
View SourceEmail 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 systememail_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 eventsemail_retention_days- Days to keep emails (default: 90)aws_ses_configuration_set- AWS SES configuration set nameemail_compress_body- Compress body after N daysemail_archive_to_s3- Enable S3 archivalemail_sampling_rate- Percentage of emails to fully log
Core Functions
System Management
enabled?/0- Check if email system is enabledenable_system/0- Enable email systemdisable_system/0- Disable email systemget_config/0- Get current system configuration
Email Log Management
list_logs/1- Get emails with filtersget_log!/1- Get email log by IDcreate_log/1- Create new email logupdate_log_status/2- Update log status
Event Management
create_event/1- Create system eventlist_events_for_log/1- Get events for specific logprocess_webhook_event/1- Process incoming webhook
Analytics & Metrics
get_system_stats/1- Overall system statisticsget_engagement_metrics/1- Open/click rate analysisget_campaign_stats/1- Campaign-specific metricsget_provider_performance/1- Provider comparison
Maintenance
cleanup_old_logs/1- Remove old logscompress_old_bodies/1- Compress storagearchive_to_s3/1- Archive to S3
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
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"}
Checks if AWS credentials are configured.
Checks both Settings Database and environment variables (Settings DB takes priority).
Examples
iex> PhoenixKit.Emails.aws_configured?()
true
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
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
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
Creates an email system event.
Examples
iex> PhoenixKit.Emails.create_event(%{
email_log_id: 1,
event_type: "open"
})
{:ok, %Event{}}
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{}}
Deletes an email log.
Examples
iex> log = PhoenixKit.Emails.get_log!(1)
iex> PhoenixKit.Emails.delete_log(log)
{:ok, %Log{}}
Disables the email system.
Sets the "email_enabled" setting to false.
Examples
iex> PhoenixKit.Emails.disable_system()
{:ok, %Setting{}}
Enables the email system.
Sets the "email_enabled" setting to true.
Examples
iex> PhoenixKit.Emails.enable_system()
{:ok, %Setting{}}
Checks if the email system is enabled.
Returns true if the "email_enabled" setting is true.
Examples
iex> PhoenixKit.Emails.enabled?()
true
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 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.
Gets AWS access key with Settings DB priority.
Priority: Settings Database → Environment Variables
Examples
iex> PhoenixKit.Emails.get_aws_access_key()
"AKIA..."
Gets the AWS region for SES and SQS services.
Examples
iex> PhoenixKit.Emails.get_aws_region()
"eu-north-1"
Gets AWS secret key with Settings DB priority.
Priority: Settings Database → Environment Variables
Examples
iex> PhoenixKit.Emails.get_aws_secret_key()
"secret..."
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
}
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"
}
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, ...]
}
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
}
Gets geographic distribution of engagement events.
Examples
iex> PhoenixKit.Emails.get_geo_stats("open", :last_30_days)
%{"US" => 500, "CA" => 200, "UK" => 150}
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{}
Gets an email log by message ID.
Examples
iex> PhoenixKit.Emails.get_log_by_message_id("msg-abc123")
%Log{}
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}
}
Gets the configured retention period for emails in days.
Examples
iex> PhoenixKit.Emails.get_retention_days()
90
Gets the sampling rate for email logging (percentage).
Examples
iex> PhoenixKit.Emails.get_sampling_rate()
100 # Log 100% of emails
Gets the AWS SES configuration set name.
Examples
iex> PhoenixKit.Emails.get_ses_configuration_set()
"my-app-system"
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"
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
}
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"
Gets the maximum number of SQS messages to receive per polling cycle.
Examples
iex> PhoenixKit.Emails.get_sqs_max_messages()
10
Gets the SQS polling interval in milliseconds.
Examples
iex> PhoenixKit.Emails.get_sqs_polling_interval()
5000 # 5 seconds
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"
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"
Gets the SQS message visibility timeout in seconds.
Examples
iex> PhoenixKit.Emails.get_sqs_visibility_timeout()
300 # 5 minutes
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
}
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}
}
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}, ...]
Lists events for a specific email log.
Examples
iex> PhoenixKit.Emails.list_events_for_log(123)
[%Event{}, ...]
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{}, ...]
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{}}
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
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
Checks if AWS SES event management is enabled.
Examples
iex> PhoenixKit.Emails.ses_events_enabled?()
true
Sets the AWS region for SES and SQS services.
Examples
iex> PhoenixKit.Emails.set_aws_region("eu-north-1")
{:ok, %Setting{}}
Sets the number of days after which to compress email bodies.
Examples
iex> PhoenixKit.Emails.set_compress_after_days(30)
{:ok, %Setting{}}
Sets the retention period for emails.
Examples
iex> PhoenixKit.Emails.set_retention_days(180)
{:ok, %Setting{}}
Enables or disables S3 archival for old email data.
Examples
iex> PhoenixKit.Emails.set_s3_archival(true)
{:ok, %Setting{}}
Sets the sampling rate for email logging.
Examples
iex> PhoenixKit.Emails.set_sampling_rate(80) # Log 80% of emails
{:ok, %Setting{}}
Enables or disables full email body saving.
Examples
iex> PhoenixKit.Emails.set_save_body(true)
{:ok, %Setting{}}
Enables or disables email headers saving.
Examples
iex> PhoenixKit.Emails.set_save_headers(true)
{:ok, %Setting{}}
Sets the AWS SES configuration set name.
Examples
iex> PhoenixKit.Emails.set_ses_configuration_set("my-system-set")
{:ok, %Setting{}}
Enables or disables AWS SES event management.
Examples
iex> PhoenixKit.Emails.set_ses_events(true)
{:ok, %Setting{}}
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{}}
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{}}
Sets the maximum number of SQS messages to receive per polling cycle.
Examples
iex> PhoenixKit.Emails.set_sqs_max_messages(20)
{:ok, %Setting{}}
Enables or disables SQS polling.
Examples
iex> PhoenixKit.Emails.set_sqs_polling(true)
{:ok, %Setting{}}
Sets the SQS polling interval in milliseconds.
Examples
iex> PhoenixKit.Emails.set_sqs_polling_interval(3000) # 3 seconds
{:ok, %Setting{}}
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{}}
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{}}
Sets the SQS message visibility timeout in seconds.
Examples
iex> PhoenixKit.Emails.set_sqs_visibility_timeout(600) # 10 minutes
{:ok, %Setting{}}
Checks if SQS polling is enabled.
Examples
iex> PhoenixKit.Emails.sqs_polling_enabled?()
true
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}}
Updates the status of an email log.
Examples
iex> PhoenixKit.Emails.update_log_status(log, "delivered")
{:ok, %Log{}}