"""
Notifier - Email and Webhook Notifications
Handles SMTP emails (Mailgun) and outgoing webhooks
Compatible with Python 3.6+
"""
import requests
import logging
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from jinja2 import Template
logger = logging.getLogger('Notifier')
class Notifier:
def __init__(self, config):
self.config = config
self.enabled = config['notifications']['enabled']
# SMTP configuration
smtp_config = config['notifications'].get('smtp', {})
self.smtp_server = smtp_config.get('server')
self.smtp_port = smtp_config.get('port', 587)
self.smtp_user = smtp_config.get('user')
self.smtp_password = smtp_config.get('password')
self.sender_email = smtp_config.get('sender_email')
# Mailgun API configuration (preferred over SMTP when configured)
mailgun_config = config['notifications'].get('mailgun', {})
self.mailgun_api_key = mailgun_config.get('api_key')
self.mailgun_domain = mailgun_config.get('domain')
self.mailgun_sender = mailgun_config.get('sender_email') or self.sender_email
self.recipients = config['notifications']['recipients']
self.webhook_config = config.get('webhooks', {})
def send_email(self, template_name, recipients, data, attachments=None):
"""
Send email via SMTP (Mailgun)
Args:
template_name: Name of email template
recipients: List of email addresses or single email
data: Template data dict
attachments: List of file paths to attach (optional)
"""
if not self.enabled:
logger.info("Notifications disabled, skipping email")
return
if not self.mailgun_api_key and (not self.smtp_server or not self.smtp_user):
logger.warning("Neither Mailgun API nor SMTP configured, skipping email")
return
try:
# Simple templates (full template system would load from YAML)
templates = {
'a1_to_a2_complete': {
'subject': "â
Master Assets Downloaded - Campaign {campaign_name}",
'html': """
â
Master Assets Downloaded Successfully
Campaign: {{ campaign_name }} ({{ campaign_number }})
Total Assets: {{ asset_count }}
{% if existing_asset_count and existing_asset_count > 0 %}
({{ existing_asset_count }} previously downloaded, {{ new_asset_count }} new this run)
{% endif %}
Status Updated: A1 â A2
{% if new_assets is defined %}
{% if new_assets|length > 0 %}
đ New This Run ({{ new_assets|length }}):
{% for asset in new_assets %}
{{ asset.asset_name }}
Tracking ID: {{ asset.tracking_id }}
Box File ID: {{ asset.box_file_id }}
Box URL: {{ asset.box_url }}
{% if asset.folder_path %}
DAM Path: {{ asset.folder_path }}
{% endif %}
{% endfor %}
{% endif %}
{% if existing_assets is defined and existing_assets|length > 0 %}
đ Previously Downloaded ({{ existing_assets|length }}):
These files were already in Box from an earlier run and were skipped.
{% for asset in existing_assets %}
- {{ asset.asset_name }}
({{ asset.tracking_id }})
{% endfor %}
{% endif %}
{% else %}
Processed Assets:
{% for asset in processed_assets %}
{{ asset.asset_name }}
Tracking ID: {{ asset.tracking_id }}
Box File ID: {{ asset.box_file_id }}
Box URL: {{ asset.box_url }}
{% if asset.folder_path %}
DAM Path: {{ asset.folder_path }}
{% endif %}
{% endfor %}
{% endif %}
â Complete: All assets downloaded from DAM and uploaded to Box with tracking IDs.
Campaign status updated from A1 to A2. Box Folder: 348304357505 (Local Adaptation)
"""
},
'a2_to_a3_complete': {
'subject': "â
Localized Assets Uploaded - Campaign {campaign_name}",
'html': """
â
Localized Assets Uploaded Successfully
Campaign: {{ campaign_name }}
Campaign ID: {{ campaign_id }}
Assets Uploaded: {{ asset_count }}
Status Updated: A2 â A3
â Complete: All localized assets have been uploaded to DAM.
Campaign status updated from A2 to A3.
"""
},
'a2_to_a3_batch_complete': {
'subject': "A2âA3 Batch Upload Complete - {successful_count}/{total_files} Successful",
'html': """
{% if failed_count == 0 %}â
Batch Upload Complete{% else %}â ī¸ Batch Upload Partial{% endif %}
Total Files: {{ total_files }}
â Successful: {{ successful_count }}
â Failed: {{ failed_count }}
Source Folder: {{ box_folder }}
{% if successful_files %}
â
Successfully Uploaded ({{ successful_count }}):
{% for asset in successful_files %}
{{ asset.clean_filename }}
Original File: {{ asset.filename }}
Tracking ID: {{ asset.tracking_id }}
DAM Asset ID: {{ asset.asset_id }}
{% if asset.subfolder_path %}
Folder Path: {{ asset.subfolder_path }}
{% endif %}
{% if asset.creativex_found %}
CreativeX Score: {{ asset.creativex_score }}
{% endif %}
{% endfor %}
{% endif %}
{% if failed_files %}
â Failed Uploads ({{ failed_count }}):
{% for asset in failed_files %}
{{ asset.filename }}
Error: {{ asset.error }}
{% if asset.tracking_id %}
Tracking ID: {{ asset.tracking_id }}
{% endif %}
{% if asset.subfolder_path %}
Folder Path: {{ asset.subfolder_path }}
{% endif %}
{% endfor %}
{% endif %}
Status: Batch processing complete.
"""
},
'upload_failed': {
'subject': "â Upload Failed - {filename}",
'html': """
â Upload Failed
Filename: {{ filename }}
Tracking ID: {{ tracking_id }}
đ Action Required: Please investigate the error and retry the upload.
"""
},
'a1_to_a2_partial': {
'subject': "â ī¸ Partial Download - Campaign {campaign_name}",
'html': """
â ī¸ Campaign Partially Processed
Campaign: {{ campaign_name }} ({{ campaign_number }})
Total Assets: {{ total_assets }}
Successful: {{ successful }} | Failed: {{ failed }}
{% if successful > 0 %}
â
Successfully Processed ({{ successful }}):
{% for asset in processed_assets %}
{{ asset.asset_name }}
Tracking ID: {{ asset.tracking_id }}
Box File ID: {{ asset.box_file_id }}
Box URL: {{ asset.box_url }}
{% if asset.folder_path %}
DAM Path: {{ asset.folder_path }}
{% endif %}
{% endfor %}
{% endif %}
{% if failed > 0 %}
â Failed Assets ({{ failed }}):
{% for asset in failed_assets %}
{% endfor %}
{% endif %}
â ī¸ Status NOT updated. Campaign remains at A1.
The script will retry failed assets on the next run (every 5 minutes).
"""
},
'a2_to_a3_file_uploaded': {
'subject': "â
Asset Uploaded to DAM - {clean_filename}",
'html': """
â
Asset Uploaded Successfully (A2âA3)
Original Filename (from Box): {{ filename }}
Clean Filename (in DAM): {{ clean_filename }}
DAM Asset ID: {{ asset_id }}
Tracking ID: {{ tracking_id }}
Processing Details:
Master Asset ID: {{ master_asset_name }}
Uploaded to DAM Folder: {{ upload_folder }}
Downloaded from Box Folder: {{ box_folder }}
What Was Done:
- â
Downloaded from Box processing folder (348526703108)
- â
Loaded master metadata from database ({{ tracking_id }})
- â
Built asset representation with 27 MVP fields
- â
Updated Description from filename
- â
Updated Language from filename
- â
Set State to "Local"
{% if creativex_found %}
- â
CreativeX Score Added: {{ creativex_score }} (from database)
{% else %}
- â ī¸ CreativeX Score: Not found - used default (0)
{% endif %}
- â
Stripped OMG Job Number and Tracking ID from filename
- â
Uploaded to DAM Final Assets folder
- â
Deleted file from Box
{% if not creativex_found %}
â ī¸ CreativeX Score Missing
No CreativeX score found in database for: {{ clean_filename }}
Default Values Used:
- Score: 0
- URL: None (no CreativeX URL sent)
To add CreativeX score: Upload PDF report to Box folder 350605024645 and run creativex_scoring_storing.py
{% endif %}
Status: Asset processing complete.
Note: Campaign status will be updated to A3 once all assets are uploaded.
"""
},
'b1_to_b2_complete': {
'subject': "â
Global Master Assets Downloaded - Campaign {campaign_name}",
'html': """
â
Global Master Assets Downloaded Successfully
Campaign: {{ campaign_name }} ({{ campaign_number }})
Campaign Type: Global Masters
Total Assets: {{ asset_count }}
{% if existing_asset_count and existing_asset_count > 0 %}
({{ existing_asset_count }} previously downloaded, {{ new_asset_count }} new this run)
{% endif %}
Status Updated: B1 â B2
{% if new_assets is defined %}
{% if new_assets|length > 0 %}
đ New This Run ({{ new_assets|length }}):
{% for asset in new_assets %}
{{ asset.asset_name }}
Tracking ID: {{ asset.tracking_id }}
Box File ID: {{ asset.box_file_id }}
Box URL: {{ asset.box_url }}
CreativeX Score: {% if asset.creativex_score %}{{ asset.creativex_score }}{% if asset.creativex_url %} (View on CreativeX){% endif %}{% else %}No CreativeX Score{% endif %}
{% if asset.folder_path %}
DAM Path: {{ asset.folder_path }}
{% endif %}
{% endfor %}
{% endif %}
{% if existing_assets is defined and existing_assets|length > 0 %}
đ Previously Downloaded ({{ existing_assets|length }}):
These files were already in Box from an earlier run and were skipped.
{% for asset in existing_assets %}
- {{ asset.asset_name }}
({{ asset.tracking_id }}) — CreativeX: {% if asset.creativex_score %}{{ asset.creativex_score }}{% else %}none{% endif %}
{% endfor %}
{% endif %}
{% else %}
Processed Assets:
{% for asset in processed_assets %}
{{ asset.asset_name }}
Tracking ID: {{ asset.tracking_id }}
Box File ID: {{ asset.box_file_id }}
Box URL: {{ asset.box_url }}
CreativeX Score: {% if asset.creativex_score %}{{ asset.creativex_score }}{% if asset.creativex_url %} (View on CreativeX){% endif %}{% else %}No CreativeX Score{% endif %}
{% if asset.folder_path %}
DAM Path: {{ asset.folder_path }}
{% endif %}
{% endfor %}
{% endif %}
â Complete: All Global Master assets downloaded from DAM and uploaded to Box with tracking IDs.
Campaign status updated from B1 to B2. Box Folder: 349261192115 (Global Masters)
"""
},
'b1_to_b2_partial': {
'subject': "â ī¸ Partial Download - Global Campaign {campaign_name}",
'html': """
â ī¸ Global Campaign Partially Processed
Campaign: {{ campaign_name }} ({{ campaign_number }})
Campaign Type: Global Masters (B1âB2)
Total Assets: {{ total_assets }}
Successful: {{ successful }} | Failed: {{ failed }}
{% if successful > 0 %}
â
Successfully Processed ({{ successful }}):
{% for asset in processed_assets %}
{{ asset.asset_name }}
Tracking ID: {{ asset.tracking_id }}
Box URL: {{ asset.box_url }}
CreativeX Score: {% if asset.creativex_score %}{{ asset.creativex_score }}{% if asset.creativex_url %} (View on CreativeX){% endif %}{% else %}No CreativeX Score{% endif %}
{% if asset.folder_path %}
DAM Path: {{ asset.folder_path }}
{% endif %}
{% endfor %}
{% endif %}
{% if failed > 0 %}
â Failed Assets ({{ failed }}):
{% for asset in failed_assets %}
{% endfor %}
{% endif %}
â ī¸ Status NOT updated. Campaign remains at B1.
The script will retry failed assets on the next run (every 5 minutes).
"""
},
'a5_to_a6_rejections': {
'subject': "â ī¸ NOT APPROVED Assets - Rework Required - Campaign {campaign_name}",
'html': """
â ī¸ NOT APPROVED ASSETS - REWORK REQUIRED
â ī¸ Campaign: {{ campaign_name }} ({{ campaign_number }})
NOT APPROVED assets: {{ rejected_count }} | Approved/skipped: {{ skipped_count }}
Status Updated: A5 â A6
{% for asset in rejected_assets %}
{{ asset.asset_name }}
Status: NOT APPROVED
Tracking ID: {{ asset.tracking_id }}{% if asset.is_existing %} (Updated existing){% endif %}
Box URL: {{ asset.box_url }}
{% if asset.folder_path %}
DAM Path: {{ asset.folder_path }}
{% endif %}
{# Rejection details commented out
{% if asset.rejection_details %}
{% set approver = asset.rejection_details.approver %}
{% set legal = asset.rejection_details.legal %}
{% set ia_cc = asset.rejection_details.ia_cc %}
{% if approver.comment %}
đ´ APPROVER REJECTION
Reason: {{ approver.comment }}
{% if approver.certifier_name %}
Rejected By: {{ approver.certifier_name }}
{% endif %}
{% if approver.date %}
Date: {{ approver.date }}
{% endif %}
{% endif %}
{% if legal.comment %}
âī¸ LEGAL REJECTION
Reason: {{ legal.comment }}
{% if legal.certifier_name %}
Rejected By: {{ legal.certifier_name }}
{% endif %}
{% if legal.date %}
Date: {{ legal.date }}
{% endif %}
{% endif %}
{% if ia_cc.comment %}
đ IA&CC REJECTION
Reason: {{ ia_cc.comment }}
{% if ia_cc.certifier_name %}
Rejected By: {{ ia_cc.certifier_name }}
{% endif %}
{% if ia_cc.date %}
Date: {{ ia_cc.date }}
{% endif %}
{% endif %}
{% if not approver.comment and not legal.comment and not ia_cc.comment %}
(No specific rejection comments available)
{% endif %}
{% else %}
(No rejection details available)
{% endif %}
#}
{% endfor %}
đ Next Steps: Please review and rework the above assets according to the rejection comments.
All rejected assets have been downloaded to Box Revisions folder (349441822875). Campaign status updated A5 â A6.
"""
},
'a5_to_a6_partial': {
'subject': "â ī¸ Partial Rework Download - Campaign {campaign_name}",
'html': """
Rework Campaign Partially Processed (A5âA6)
Campaign: {{ campaign_name }} ({{ campaign_id }})
Campaign Number: {{ campaign_number }}
Total NOT APPROVED: {{ total_assets }}
Successful: {{ successful }}
Failed: {{ failed }}
{% if successful > 0 %}
â
Successfully Processed ({{ successful }}):
{% for asset in rejected_assets %}
- {{ asset.asset_name }}
Tracking ID: {{ asset.tracking_id }}{% if asset.is_existing %} (Updated existing){% endif %}
Box URL: {{ asset.box_url }}
{% endfor %}
{% endif %}
{% if failed > 0 %}
â Failed Assets ({{ failed }}):
{% for asset in failed_assets %}
- {{ asset.asset_name }}
Error: {{ asset.error }}
{% endfor %}
{% endif %}
Status NOT updated. Campaign remains at A5.
The script will retry failed assets on the next run (every 5 minutes).
"""
},
'a5_to_a6_no_rejections': {
'subject': "â
No Rework Required - Campaign {campaign_name}",
'html': """
â
No Rework Required
Campaign: {{ campaign_name }} ({{ campaign_number }})
Total assets checked: {{ total_assets }}
Approved/other status: {{ skipped_count }}
NOT APPROVED assets: 0
Good News!
All assets in the Final Assets folder are approved or have other status.
No assets with "NOT APPROVED" status were found, so no rework is required.
đ Note:
- No downloads were performed
- Status NOT updated (remains A5)
- Script will check again on next run
A5âA6 script completed successfully with no rejected assets found.
"""
},
'a1_to_a2_no_assets': {
'subject': "â ī¸ No Assets Found - Campaign {campaign_name}",
'html': """
â ī¸ No Master Assets Found
Campaign: {{ campaign_name }} ({{ campaign_number }})
Campaign ID: {{ campaign_id }}
Status: A1
Campaign Set to A1 but No Assets Found
The Master Assets folder was searched (including subfolders) but no assets were found.
This campaign is set to status A1 but appears to have no master assets ready for download.
đ What Happens Next:
- No downloads were performed
- Status NOT updated (remains A1)
- Script will check again on next run (every 5 minutes)
- Please verify assets exist in Master Assets folder
A1âA2 script completed with no assets to process.
"""
},
'a1_to_a2_no_assets_retry': {
'subject': "â ī¸ No Assets Found (Attempt {retry_count}/3) - Campaign {campaign_name}",
'html': """
â ī¸ No Master Assets Found (Retry {{ retry_count }}/{{ max_retries }})
Campaign: {{ campaign_name }} ({{ campaign_number }})
Campaign ID: {{ campaign_id }}
Status: A1
Retry Attempt: {{ retry_count }} of {{ max_retries }}
Campaign Set to A1 but No Assets Found
The Master Assets folder was searched (including subfolders) but no assets were found.
This campaign is set to status A1 but appears to have no master assets ready for download.
đ What Happens Next:
- This is attempt {{ retry_count }} of {{ max_retries }}
- System will retry automatically on next run (every 3 minutes)
{% if retry_count < max_retries %}
- {{ max_retries - retry_count }} attempt(s) remaining before marking as permanently failed
{% else %}
- WARNING: This is the final attempt! Next failure will mark campaign as permanently failed.
{% endif %}
- Please verify assets exist in Master Assets folder
A1âA2 script will retry automatically. No action needed unless this persists.
"""
},
'a1_to_a2_no_assets_warning': {
'subject': "â ī¸ Campaign in A1 with no assets yet - {campaign_name}",
'html': """
â ī¸ Campaign in A1 with No Assets Yet
Campaign: {{ campaign_name }} ({{ campaign_number }})
Campaign ID: {{ campaign_id }}
Status: A1
Polls with empty folder: {{ poll_count }}
Master Assets Folder Has Been Empty for ~1 Hour
This campaign has been at status A1 for roughly an hour with no master assets in the folder.
This is often expected â the folder may have been created before assets were uploaded â and the system will keep checking automatically.
This is a one-time warning; no further emails will be sent for this campaign.
đ Action only needed if:
- You expected assets to be uploaded already
- The campaign was set to A1 by mistake (change the status in DAM)
Otherwise no action needed â processing will start automatically as soon as assets appear in the Master Assets folder.
A1âA2 script will continue to check silently every 3 minutes.
"""
},
'a1_to_a2_permanently_failed': {
'subject': "â PERMANENTLY FAILED - Campaign {campaign_name} (No Assets After 3 Attempts)",
'html': """
â CAMPAIGN PERMANENTLY FAILED
Campaign: {{ campaign_name }} ({{ campaign_number }})
Campaign ID: {{ campaign_id }}
Status: A1
Failed Attempts: {{ retry_count }} / {{ max_retries }}
Campaign Marked as Permanently Failed
After {{ max_retries }} consecutive attempts, the system was unable to find any master assets in the Master Assets folder.
This campaign will no longer be processed automatically.
đ§ Required Actions:
- Verify the campaign should actually be in A1 status
- Check if Master Assets folder exists and contains files
- If this is a mistake, change campaign status to something else
- If assets need to be added, add them to Master Assets folder
- Once fixed, manually reset the retry counter
đĄ How to Reset This Campaign:
To reset the status and retry this campaign, please contact support at:
optical@oliver.agency
Support will reset the retry counter and investigate the issue.
Automated processing stopped. Manual intervention required.
"""
},
'b1_to_b2_no_assets': {
'subject': "â ī¸ No Assets Found - Global Campaign {campaign_name}",
'html': """
â ī¸ No Global Master Assets Found
Campaign: {{ campaign_name }} ({{ campaign_number }})
Campaign ID: {{ campaign_id }}
Status: B1
Campaign Type: Global Masters
Campaign Set to B1 but No Assets Found
The Final Assets folder was searched (including subfolders) but no assets were found.
This Global Masters campaign is set to status B1 but appears to have no assets ready for download.
đ What Happens Next:
- No downloads were performed
- Status NOT updated (remains B1)
- Script will check again on next run (every 5 minutes)
- Please verify assets exist in Final Assets folder
B1âB2 script completed with no assets to process.
"""
},
'a4_webhook_sent': {
'subject': "đĸ A4 Campaign Webhook Sent - {campaign_name}",
'html': """
đĸ A4 Campaign Webhook Sent
Campaign: {{ campaign_name }} ({{ campaign_number }})
Status: A4 (Not Going Live)
Live Campaign: NO
Webhook Notification Sent
A webhook notification has been sent indicating this campaign is marked as A4 and will not go live.
Webhook URL: {{ webhook_url }}
Payload Sent:
- campaign_id: {{ campaign_id }}
- campaign_number: {{ campaign_number }}
- campaign_name: {{ campaign_name }}
- status: A4
- live_campaign: NO
A4 webhook monitor completed successfully.
"""
},
'daily_report': {
'subject': "đ Ferrero Automation Daily Report - {report_date}",
'html': """
đ Ferrero Automation Daily Report
{{ report_date }} - Generated at {{ report_time }}
đ Overall Summary (Last 24 Hours)
Campaigns Found: {{ total_stats.campaigns_found }}
Campaigns Processed: {{ total_stats.campaigns_processed }}
â
Completed: {{ total_stats.campaigns_completed }}
â ī¸ Partial: {{ total_stats.campaigns_partial }}
No Assets: {{ total_stats.campaigns_no_assets }}
Total Assets: {{ total_stats.total_assets }}
â Successful: {{ total_stats.assets_successful }}
â Failed: {{ total_stats.assets_failed }}
{% if total_stats.assets_skipped > 0 %}
Skipped (Approved): {{ total_stats.assets_skipped }}
{% endif %}
{% if total_stats.not_approved_count > 0 %}
đ´ NOT APPROVED: {{ total_stats.not_approved_count }}
{% endif %}
{% if total_stats.total_assets > 0 %}
Success Rate:
{{ "%.1f"|format(total_stats.success_rate) }}%
{% endif %}
đ Workflow Breakdown
{% for workflow_name, stats in workflow_stats.items() %}
{{ workflow_name }}
{% if stats.campaigns_processed > 0 %}
Campaigns: {{ stats.campaigns_processed }}
Assets: {{ stats.total_assets }}
â Successful: {{ stats.assets_successful }}
â Failed: {{ stats.assets_failed }}
{% if stats.assets_skipped > 0 %}
Skipped: {{ stats.assets_skipped }}
{% endif %}
{% if stats.not_approved_count > 0 %}
NOT APPROVED: {{ stats.not_approved_count }}
{% endif %}
{% if stats.campaign_details %}
View Campaign Details ({{ stats.campaign_details|length }})
{% for campaign in stats.campaign_details %}
{{ campaign.name }} ({{ campaign.number }})
Total: {{ campaign.total_assets }}, Success: {{ campaign.successful }}, Failed: {{ campaign.failed }}{% if campaign.get('skipped') %}, Skipped: {{ campaign.skipped }}{% endif %}
{% endfor %}
{% endif %}
{% if stats.errors %}
â ī¸ Errors ({{ stats.errors|length }})
{% for error in stats.errors[:10] %}
{{ error }}
{% endfor %}
{% if stats.errors|length > 10 %}
... and {{ stats.errors|length - 10 }} more errors
{% endif %}
{% endif %}
{% else %}
No activity in the last 24 hours
{% endif %}
{% endfor %}
đ Automation Scripts: A1âA2, A2âA3, A5âA6, B1âB2
Scripts run every 5 minutes | Report generated daily at 7:00 PM
"""
},
'creativex_complete': {
'subject': "â
CreativeX Scores Extracted - {file_count} files processed",
'html': """
â
CreativeX Score Extraction Complete
Files Processed: {{ file_count }}
Scores Extracted: {{ success_count }}
Source: Box Folder 350605024645
Extracted Scores:
{% for score in processed_files %}
{{ score.filename }}
{% if score.version_number > 1 %}Version {{ score.version_number }}{% if score.is_update %} (Updated){% endif %}{% endif %}
Quality Score: {{ score.quality_score }}
CreativeX ID: {{ score.creativex_id }}
{% if score.creativex_url %}
CreativeX URL: {{ score.creativex_url }}
{% endif %}
Box File ID: {{ score.box_file_id }}
{% if score.version_number > 1 %}
đ Note: This is version {{ score.version_number }} of this file (previous versions preserved in database)
{% endif %}
{% endfor %}
â Complete: All scores extracted and stored in database.
Files Removed: Processed PDFs deleted from Box folder.
CreativeX scores stored with full JSON for future lookups.
"""
},
'creativex_partial': {
'subject': "â ī¸ CreativeX Extraction Partial - {success_count}/{file_count} successful",
'html': """
â ī¸ CreativeX Extraction Partially Complete
Total Files: {{ file_count }}
â Successful: {{ success_count }}
â Failed: {{ failed_count }}
Source: Box Folder 350605024645
{% if processed_files %}
â
Successful Extractions ({{ success_count }}):
{% for score in processed_files %}
{{ score.filename }} - Score: {{ score.quality_score }}
{% if score.version_number > 1 %} (Version {{ score.version_number }}){% endif %}
{% endfor %}
{% endif %}
{% if failed_files %}
â Failed Extractions ({{ failed_count }}):
{% for file in failed_files %}
{{ file.filename }}
Error: {{ file.error }}
{% endfor %}
{% endif %}
â ī¸ Action Required: Review failed extractions above.
Failed files remain in Box folder for retry.
Successful scores stored in database. Failed files not deleted from Box.
"""
},
'creativex_no_files': {
'subject': "âšī¸ CreativeX Extraction - No files found",
'html': """
âšī¸ CreativeX Extraction - No Files
Status: No PDF files found
Source: Box Folder 350605024645
Run Time: {{ timestamp }}
âšī¸ Note: This is expected behavior when no new PDFs are ready for processing.
Upload PDFs to Box folder 350605024645 to process CreativeX scores.
Script completed successfully with no errors.
"""
},
'a5_to_a6_no_rejections': {
'subject': "â
No Rework Required - Campaign {campaign_name}",
'html': """
# ... (template content skipped for brevity)
"""
}
}
except Exception as e:
logger.error("Error creating templates: {}".format(str(e)))
return
try:
# 1. Prepare message content
template = templates.get(template_name)
if not template:
logger.error("Email template not found: {}".format(template_name))
return
jinja_template = Template(template['html'])
html_content = jinja_template.render(data)
subject = template['subject'].format(**data)
# 2. Send via Mailgun API or SMTP
recipient_list = recipients if isinstance(recipients, list) else [recipients]
if self.mailgun_api_key and self.mailgun_domain:
self._send_via_mailgun_api(recipient_list, subject, html_content, attachments)
else:
self._send_via_smtp(recipient_list, subject, html_content, attachments)
logger.info("Email sent to {} (Template: {})".format(recipients, template_name))
except Exception as e:
logger.error("Failed to send email: {}".format(str(e)))
def _send_via_mailgun_api(self, recipient_list, subject, html_content, attachments=None):
"""Send email via Mailgun REST API - sends one request per recipient for reliable delivery"""
import os
url = "https://api.mailgun.net/v3/{}/messages".format(self.mailgun_domain)
# Normalize: split any comma-separated strings into individual addresses
normalized = []
for r in recipient_list:
for addr in r.split(','):
addr = addr.strip()
if addr:
normalized.append(addr)
for recipient in normalized:
files = []
try:
if attachments:
for file_path in attachments:
if os.path.exists(file_path):
files.append(("attachment", (os.path.basename(file_path), open(file_path, "rb"))))
else:
logger.warning("Attachment not found: {}".format(file_path))
data = {
"from": self.mailgun_sender,
"to": [recipient],
"subject": subject,
"html": html_content,
}
response = requests.post(
url,
auth=("api", self.mailgun_api_key),
data=data,
files=files if files else None,
)
response.raise_for_status()
logger.info("Mailgun API sent to {}: {}".format(recipient, response.json()))
except Exception as e:
logger.error("Mailgun API failed for {}: {}".format(recipient, str(e)))
finally:
for _, file_tuple in files:
file_tuple[1].close()
def _send_via_smtp(self, recipient_list, subject, html_content, attachments=None):
"""Send email via SMTP"""
import os
from email.mime.base import MIMEBase
from email import encoders
if attachments:
message = MIMEMultipart()
message['From'] = self.sender_email
message['To'] = ", ".join(recipient_list)
message['Subject'] = subject
message.attach(MIMEText(html_content, "html"))
for file_path in attachments:
try:
if os.path.exists(file_path):
with open(file_path, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
filename = os.path.basename(file_path)
part.add_header(
"Content-Disposition",
"attachment; filename= {}".format(filename),
)
message.attach(part)
logger.info("Attached file: {}".format(filename))
else:
logger.warning("Attachment not found: {}".format(file_path))
except Exception as e:
logger.error("Failed to attach file {}: {}".format(file_path, str(e)))
else:
message = MIMEText(html_content, "html")
message['From'] = self.sender_email
message['To'] = ", ".join(recipient_list)
message['Subject'] = subject
with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:
server.starttls()
server.login(self.smtp_user, self.smtp_password)
server.send_message(message)
def send_webhook(self, url, payload):
"""
url: Webhook URL
payload: dict to send as JSON
Returns:
bool: Success status
"""
try:
# Get webhook config if exists
webhook_config = None
for name, config in self.webhook_config.items():
if config.get('url') == url:
webhook_config = config
break
if not webhook_config:
webhook_config = {'timeout_seconds': 10, 'auth': {}}
# Prepare headers
headers = {'Content-Type': 'application/json'}
# Add auth if configured
auth_config = webhook_config.get('auth', {})
if auth_config.get('type') == 'bearer' and auth_config.get('token'):
headers['Authorization'] = 'Bearer {}'.format(auth_config['token'])
elif auth_config.get('type') == 'basic':
# Could add basic auth here if needed
pass
# Send webhook
response = requests.post(
url,
json=payload,
headers=headers,
timeout=webhook_config.get('timeout_seconds', 10)
)
if response.status_code in [200, 201, 202]:
logger.info("Webhook sent successfully: {}".format(url))
return True
else:
logger.warning("Webhook failed: HTTP {} - {}".format(
response.status_code, response.text[:200]
))
return False
except Exception as e:
logger.error("Webhook error: {}".format(str(e)))
return False