Installation and configuration guide
1. Requirements
The module is intended for Magento 2 and Composer-managed installations.
Required:
- a Composer-managed Magento 2 project,
- a PHP version compatible with the Magento installation in use,
- access to Magento CLI,
- OpenAI API key,
- a running Magento Message Queue consumer process.
Module package:
kowal/module-ai-email-theme-generator
Magento module name:
Kowal_AiEmailThemeGenerator
2. Installation
Add the Composer repository:
composer config repositories.ai.email.theme.generator vcs https://github.com/kowalco/ai-email-theme-generator
If the repository is private, configure GitHub authentication:
composer config --global --auth github-oauth.github.com
Install the module:
composer require kowal/module-ai-email-theme-generator
Enable the module:
bin/magento module:enable Kowal_AiEmailThemeGenerator
Run the Magento upgrade:
bin/magento setup:upgrade
Flush the cache:
bin/magento cache:flush
For production mode, run the standard deployment commands used in the project, for example:
bin/magento setup:di:compilebin/magento setup:static-content:deploybin/magento cache:flush
3. Queue Consumer
AI generation is processed asynchronously through Magento Message Queue.
Start the consumer manually:
bin/magento queue:consumers:start kowal.ai_email.generate.consumer
In production environments, configure the consumer under supervisor, systemd, or another process manager used by the hosting environment.
The module creates jobs in the admin panel, but the AI request will not be processed until the consumer is running.
4. Administrator permissions
The module adds ACL resources:
Kowal_AiEmailThemeGenerator::rootKowal_AiEmailThemeGenerator::jobsKowal_AiEmailThemeGenerator::generateKowal_AiEmailThemeGenerator::retryKowal_AiEmailThemeGenerator::cancelKowal_AiEmailThemeGenerator::applyKowal_AiEmailThemeGenerator::deleteKowal_AiEmailThemeGenerator::settings
To allow an administrator to use the module, assign the appropriate resources in:
System > Permissions > User Roles
For full access, allow the main AI Email Generation resource and all child resources.
5. Configuration location
Go to:
Stores > Configuration > AI Email Generation > AI Email Theme Generator
The configuration section contains the group:
General Settings
6. Configuration fields
Enabled
Type: Yes/No
Default: No
Enables or disables the module features.
When set to No:
- the module should not create AI generation jobs,
- the generation action is blocked,
- the administrator should configure the module first.
Set Yes only after preparing the API key and starting the queue consumer.
API Provider
Type: Select
Default: OpenAI
Defines the AI provider used by the module.
The current implementation supports:
OpenAI
The field exists so that more providers can be added in the future without changing the administrator workflow.
OpenAI API Key
Type: hidden/encrypted field
Stores the OpenAI API key used for generation.
The value is encrypted by Magento using:
MagentoConfigModelConfigBackendEncrypted
Important:
- do not place the API key directly in the code,
- do not commit environment keys,
- restrict access to this field through ACL,
- use a key with permissions appropriate for the project.
OpenAI Model
Type: Select
Defines the OpenAI model used for generation.
Example:
gpt-4.1
The list is fetched dynamically from the OpenAI Models API using the configured API key. The module filters the response to GPT model identifiers and caches the list for a short time so it does not call the API every time the configuration is opened.
If the API key has not been saved yet, the field will show a fallback option and ask the administrator to save the key.
If the OpenAI API is temporarily unavailable, the field keeps the currently configured model whenever possible.
Use a model that supports the required input type:
- text generation for prompts and template content,
- a model that supports images if graphic reference designs are used.
The selected model affects result quality, response time, and cost.
Request Timeout
Type: Number
Example default value:
120
Maximum time in seconds allowed for the request to the OpenAI API.
Recommended values:
60 for short text generation,120 or more for complex HTML/CSS generation,- higher values only when the infrastructure allows longer queue jobs.
The timeout applies to background processing, not the admin form request.
Maximum Retries
Type: Number
Example default value:
2
Defines how many times the consumer can automatically retry a failed generation job.
Retries are useful for temporary errors, such as:
- API timeout,
- temporary provider error,
- rate limit,
- network issue.
Permanent errors, such as incorrect configuration or an invalid AI response, should be checked in the job details.
Technical Prompt
Type: Textarea
This prompt is applied to every generation request. It should contain technical rules that must always be followed.
Example:
You are an assistant generating Magento 2 email templates.Return only JSON that matches the provided schema.Keep Magento directives valid.Do not invent Magento variables.Do not add JavaScript.Put CSS in template_styles unless inline styles are required for email compatibility.Preserve required variables and add warnings when a requested change is risky.When assets are provided, use only the URLs from the assets section, preserve alt text, apply target links to clickable images, use banners and icons according to their sort_order, and do not invent additional image URLs.
Use this field for stable instructions, such as:
- preserving Magento directives,
- keeping required variables,
- avoiding JavaScript,
- returning JSON only,
- writing HTML compatible with email clients,
- using CSS in the correct result field.
Do not use this field for one-time creative instructions. Use AI Prompt in the template form for that.
Default User Prompt
Type: Textarea
This prompt is shown by default in the AI section of the email template editor.
Example:
Improve this Magento email template while keeping all required Magento variables and directives valid.
The administrator can change it before creating a generation job.
Use this field to set a practical default instruction for typical generation tasks.
Allowed Design File Types
Type: Text
Example default value:
png,jpg,jpeg,webp,html,htm,txt
Comma-separated list of allowed file extensions for the optional reference design.
Supported examples:
In production, use the most restrictive list possible. Do not allow file types that are not needed in the process.
Maximum Design File Size
Type: Number
Example default value:
5242880
Maximum reference file size in bytes.
Examples:
1048576 = 1 MB5242880 = 5 MB10485760 = 10 MB
Large files increase the payload size and may slow down generation or exceed provider limits.
Automatically Apply Result
Type: Yes/No
Default: No
Defines whether a valid AI result should immediately overwrite the native Magento template fields.
When set to Yes, the consumer saves the generated result to:
- Template Name
- Template Subject
- Template Content
- Template Styles
When set to No, the result is stored in the job and the administrator can review it before applying it manually.
Recommended production setting:
No
Manual approval is safer because the AI result may be technically correct but still require brand, legal, or layout review.
Keep Request and Response Payloads
Type: Yes/No
Default: Yes
Defines whether the module saves full request and response payloads in the job record.
When enabled, job details may show:
- template snapshot sent to AI,
- available variables,
- prompts,
- reference design metadata,
- AI response.
This is useful for debugging and auditing.
In production environments, review privacy requirements before enabling this option. The module should not send real customer data to AI, but payloads may still contain business-sensitive template content.
Retention Days
Type: Number
Example default value:
30
Defines how long old jobs should be stored.
This value documents the target retention policy. The project can use it to implement scheduled cleanup according to operational requirements.
7. Example: generating the New Order Confirmation for Guest template
This example describes the full process of generating an improved Magento email template for:
New Order Confirmation for Guest
Step 1: Configure the module
Go to:
Stores > Configuration > AI Email Generation > AI Email Theme Generator
Set:
Enabled = YesAPI Provider = OpenAIOpenAI API Key = OpenAI Model = gpt-4.1Request Timeout = 120Maximum Retries = 2Automatically Apply Result = NoKeep Request and Response Payloads = Yes
Save the configuration and flush the cache if Magento asks you to.
Step 2: Start the queue consumer
Run:
bin/magento queue:consumers:start kowal.ai_email.generate.consumer
During testing, the process should run continuously.
Step 3: Create a native Magento template
Go to:
Marketing > Communications > Email Templates
Click:
Add New Template
In the Template field, select:
New Order Confirmation for Guest
Click:
Load Template
Magento will populate the native fields:
- Template Subject
- Template Content
- Template Styles
Set the template name, for example:
New Order Confirmation for Guest - AI Draft
Save the template.
The AI generation process requires a saved template because the job must have a persistent template_id.
Step 4: Fill in the AI Prompt
After saving, open the template again if necessary. The standard Magento email template editor includes the AI Email Generation section.
In the AI Prompt field, enter a business instruction, for example:
Create a modern, clean transactional email for a premium fashion store.Keep all Magento order variables and directives valid.Improve the subject line and make the content easier to scan.Add a clear order summary section, shipping information section, and customer support footer.Use neutral colors, simple spacing, and email-client-safe HTML.
Purpose of this field:
- describes the expected business result,
- applies only to a specific generation job,
- can include instructions about the brand, tone of communication, layout, or content,
- should not contain API data or real customer data.
Step 5: Optionally add Design Reference
Use Design Reference if the generated email should follow a specific visual direction.
Example files:
order-email-reference.pngbrand-email-layout.webpemail-layout.htmldesign-notes.txt
Purpose of this field:
- gives AI additional visual or structural context,
- helps match the template to the graphic design,
- is optional,
- must meet file extension and size limits.
If no reference design is added, AI will use only the template content, variables, technical prompt, and user prompt.
Step 6: Optionally add Error Screenshot
Use Error Screenshot if you want to show AI the current rendering, layout, or template validation issue.
Examples:
- a screenshot of a misaligned header,
- a screenshot of a banner issue,
- an email preview with incorrect spacing,
- a screenshot from an email client showing a responsiveness issue,
- a screenshot of an error message from a testing tool.
This field is sent to AI as a separate JSON section:
{ 'error_screenshot': { 'type': 'image', 'filename': 'email-rendering-error.png', 'mime_type': 'image/png', 'content_base64': '...', 'purpose': 'current_error_context', 'description': 'Screenshot showing current rendering, layout, visual, or validation errors. Use it to understand what should be fixed. This is not a design reference.' }}
Purpose of this field:
- shows AI the current error to fix,
- is not a graphic design or a target look reference,
- helps AI understand what is currently not working,
- should be used together with a clear problem description in
AI Prompt.
Example prompt:
Use the attached error screenshot only to understand the current rendering issue.Fix the spacing problem visible in the screenshot while preserving Magento variables.Do not treat the screenshot as the target design.
Step 7: Add structured AI Assets
The editor includes an AI Assets area. These assets are saved with the Magento template and sent to AI as grouped frontend media URLs.
Available asset groups:
| Field | Meaning |
|---|
| Logo | Brand logo used in the email header or footer. |
| Header Image | Main graphic for the top part of the email. |
| Banners | Dynamic list of promotional or informational banners. |
| Icons | Dynamic list of small graphic elements, such as benefits or service icons. |
Each asset can contain:
| Field | Meaning |
|---|
| File | Image file uploaded to Magento media storage. |
| Label | Internal name that helps AI understand the purpose of the asset. |
| Alt Text | Text used in the image alt attribute. |
| Target URL | Link used when the image should be clickable. |
| Sort Order | Display priority for banners and icons. |
For banners and icons, click:
Add BannerAdd Icon
The module saves uploaded assets in Magento media storage and sends public frontend URLs to AI in the following structure:
{ 'assets': { 'logo': { 'label': 'Brand logo', 'url': 'https://example.com/media/ai_email_theme_generator/template_12/logo/logo.png', 'alt': 'Brand logo', 'link': 'https://example.com/', 'sort_order': 0 }, 'header_image': { 'label': 'Spring campaign header', 'url': 'https://example.com/media/ai_email_theme_generator/template_12/header/header.jpg', 'alt': 'Spring collection', 'link': 'https://example.com/spring', 'sort_order': 0 }, 'banners': [ { 'label': 'Main promotion', 'url': 'https://example.com/media/ai_email_theme_generator/template_12/banner/banner.jpg', 'alt': '20% off new collection', 'link': 'https://example.com/new', 'sort_order': 10 } ], 'icons': [ { 'label': 'Free delivery', 'url': 'https://example.com/media/ai_email_theme_generator/template_12/icon/delivery.png', 'alt': 'Free delivery', 'link': 'https://example.com/delivery', 'sort_order': 10 } ] }}
Refer to these groups directly in prompts. Example:
Use the uploaded logo as the main brand mark.Use the header image at the top of the email.Place banners below the order summary using their sort order.Use icons in a benefits row and link each icon to its target URL.Always preserve alt text.
Step 8: Select generation after saving
Enable:
Generate with AI after saving
Purpose of this field:
- Magento first saves the template using the standard native save action,
- after a successful save, the module creates an AI generation job,
- the uploaded reference design is attached to the job,
- the job is processed asynchronously by the queue consumer.
If the checkbox is not selected, saving the template works exactly like a standard Magento save, and no AI job is created.
Step 9: Save the template
Click the standard Magento button:
Save Template
After the template is saved, the module creates a generation job.
At this point:
- native template save is complete,
- the job status starts as
pending, - the queue consumer processes the job in the background.
Step 10: Check the job
Go to:
Marketing > Communications > AI Email Generation Jobs
Open the created job.
Key fields:
| Field | Meaning |
|---|
| Status | Current processing status. |
| Template ID | ID of the native Magento email template. |
| Template Name | Template name saved at the time the job was created. |
| Model | OpenAI model used for generation. |
| Attempts | Number of processing attempts. |
| Prompt | User prompt submitted from the template form. |
| Request Payload | JSON sent to AI if payload storage is enabled. |
| Response Payload | JSON returned by AI if payload storage is enabled. |
| Generated Result | Parsed result ready to apply. |
| Assets | Public frontend URLs and metadata for the logo, header, banners, and icons. |
| Error Screenshot | Screenshot with current errors, sent to AI as repair context. |
| Warnings | AI warnings about risky or incomplete requirements. |
| Error Message | Error cause when generation fails. |
| Status History | History of job status changes. |
Typical statuses:
| Status | Meaning |
|---|
pending | The job has been created and is waiting for the consumer. |
processing | The consumer is currently processing the job. |
retry_scheduled | The previous attempt failed and a retry has been scheduled. |
completed | AI returned a valid result. |
failed | The job failed after all attempts or validation failed. |
cancelled | The administrator canceled the job. |
Step 11: Apply the result
If Automatically Apply Result = No, the result is not automatically saved to the Magento template.
Review:
- Template Name
- Template Subject
- Template Content
- Template Styles
- Warnings
- Request Payload
- Response Payload
If the result is correct, click:
Apply Result
The module will save the generated values to the native Magento template fields.
Step 12: Verify the native email template
Return to:
Marketing > Communications > Email Templates
Open the template and check that:
- Template Name has been updated,
- Template Subject has been updated,
- Template Content contains the expected HTML and Magento directives,
- Template Styles contains the expected CSS,
- required Magento variables have not been removed.
Send a test email or run a test order flow according to the project standard QA process.
Step 13: Send another revision to AI
After applying the result with Apply Result, the current template version is saved in native Magento fields. This means the next AI request will be based on this version, not on the original template.
You can refine the same template multiple times:
- Apply the AI result with
Apply Result. - Open the template again in
Marketing > Communications > Email Templates. - Enter a new prompt describing the specific improvement.
- If the issue is visual, add
Error Screenshot. - Select
Generate with AI after saving. - Save the template.
- Review the new job and apply the result if it is correct.
For subsequent revisions, treat AI Prompt as a description of the change to the current version. It is best to specify:
- what is currently incorrect,
- what result should be achieved,
- which elements AI should not change,
- whether the attached
Error Screenshot shows a rendering error, visual layout, responsiveness issue, or validation message.
Example prompt for another revision:
Use the current saved template as the base.Fix the spacing issue visible in the attached error screenshot.Keep the current header layout, all Magento variables, and the existing Template Styles structure.Do not redesign the whole email.
This workflow is useful when the first version is close to the expected result but requires refinement of details such as spacing, responsiveness, banner visibility, logo position, or button style.
You can repeat this cycle many times. Each new job creates a separate history entry, so you can return to previous prompts, payloads, and AI responses to check which instruction led to a specific change.
8. Meaning of AI payload fields
The module sends a structured payload to AI. The most important sections are:
template
Contains the current state of the Magento template:
- template ID,
- template name,
- subject,
- content,
- styles,
- original template code.
AI uses this section as the base material for generation.
Important: if an AI result was previously applied using Apply Result, the template section already contains that updated version. This allows the next generation to work as a revision of the current template.
variables
Contains Magento variables and directives detected in the template.
AI should preserve these values and should not invent unsupported variables.
prompts
Contains:
technical - global technical prompt from configuration,user - prompt entered in the template editor.
The technical prompt protects Magento-specific structure. The user prompt describes the expected result for one template.
design_reference
Contains optional metadata and content of the uploaded reference design.
The section is empty when no reference file has been uploaded.
error_screenshot
Contains an optional screenshot showing current rendering, layout, visual, or validation errors.
This section has a purpose and description so AI knows that the file is used to understand the issue, not as a target design reference.
The section is empty when no screenshot has been uploaded.
For subsequent revisions, it is worth using error_screenshot together with a precise prompt that explains what should be fixed and what should not be changed. This allows AI to fix a specific issue without rebuilding the entire template.
Example: after applying the first AI result, the administrator notices that in Gmail the banner overlaps the order summary section. In the next request, they attach a screenshot of that view and enter a prompt asking only to fix banner spacing and width. The payload still contains the current Template Content and Template Styles, so AI works on the last saved version.
assets
Contains structured image assets saved for the template:
- logo,
- header image,
- banners,
- icons.
Each asset contains a public media URL, label, alt text, target URL, sort order, and filename.
AI should use these URLs when building HTML and should not invent additional image URLs.
store_context
Contains basic store information, such as:
- store ID,
- locale,
- base URL.
AI can use this to understand the language and context, but it should not receive real customer or order data.
9. Troubleshooting
Job remains in pending status
Most likely cause:
- the queue consumer is not running.
Check:
bin/magento queue:consumers:start kowal.ai_email.generate.consumer
Configuration page shows access denied
Check ACL permissions for:
Kowal_AiEmailThemeGenerator::settings
After changing administrator permissions, log out and log back in.
Generation ends with a missing API key error
Check:
OpenAI API Key
Make sure the module is enabled and the configuration has been saved in the correct scope.
AI result has completed status, but the template was not updated
Check:
Automatically Apply Result
If the option is set to No, open the job and click:
Apply Result
Next revision does not include the previous result
Check whether the previous result was applied using:
Apply Result
The next generation is based on the currently saved Magento template. If the job result has completed status but was not applied, the next job will still be based on the older template version.
AI response was rejected
The module validates the returned JSON. It may reject the result if:
- required fields are missing,
- required fields have invalid types,
- template name, subject, or content is empty,
- content contains a
script tag, - the result is not valid JSON.
Check the error message in the job and retry generation with a clearer prompt.
10. Recommended production settings
Recommended initial values:
Enabled = YesRequest Timeout = 120Maximum Retries = 2Automatically Apply Result = NoKeep Request and Response Payloads = Yes for testing, No or limited retention for productionRetention Days = 30
Use manual result application until the team is confident that the prompts, selected model, and validation rules produce consistent templates.