loreal-global-kickoff/EmailService.php
DJP 9b8dbbf20c Enable OMG API lookup and add SMTP email support
Email Configuration:
- Added SMTP support via Mailgun (smtp.mailgun.org:587)
- EmailService now supports both Mailgun API and SMTP
- Configured to use twist@mail.dev.oliver.solutions
- Emails sent to logged-in user (SSO email or local dev email)

OMG API:
- Enabled OMG API lookup in process-csv.php
- API key configured in config.php
- Looks up business unit from campaign number
- Falls back to 'ERROR' if business unit not recognized

SMTP Implementation:
- Full SMTP protocol with AUTH LOGIN
- Proper error handling and logging
- Fallback to Mailgun API if SMTP fails

Notifications sent to user email:
- Process started notification
- Process completed notification (with file count)
- Error notifications

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-18 08:15:22 -05:00

229 lines
7.1 KiB
PHP

<?php
/**
* Email Service
* Handles email notifications via Mailgun
*/
class EmailService {
private $config;
private $enabled;
public function __construct() {
$appConfig = require __DIR__ . '/config.php';
$this->config = $appConfig['email'];
$this->enabled = $this->config['enabled'] ?? false;
}
/**
* Send email via Mailgun API or SMTP
*/
public function send($to, $subject, $text) {
if (!$this->enabled) {
error_log('Email not sent (service disabled): ' . $subject);
return ['success' => true, 'message' => 'Email disabled'];
}
$service = $this->config['service'] ?? 'mailgun';
if ($service === 'smtp') {
return $this->sendViaSMTP($to, $subject, $text);
} else {
return $this->sendViaMailgunAPI($to, $subject, $text);
}
}
/**
* Send email via Mailgun API
*/
private function sendViaMailgunAPI($to, $subject, $text) {
try {
$url = 'https://api.mailgun.net/v3/' . $this->config['domain'] . '/messages';
$postData = [
'from' => $this->config['from'],
'to' => $to,
'subject' => $subject,
'text' => $text
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => 'api:' . $this->config['mailgun_api_key'],
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_TIMEOUT => 10
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
error_log('Email send failed: ' . $curlError);
return [
'success' => false,
'error' => 'Email delivery failed',
'details' => $curlError
];
}
if ($httpCode !== 200) {
error_log('Email send failed (HTTP ' . $httpCode . '): ' . $response);
return [
'success' => false,
'error' => 'Email service error',
'details' => 'HTTP ' . $httpCode,
'httpCode' => $httpCode
];
}
error_log('Email sent successfully to ' . $to);
return [
'success' => true,
'httpCode' => $httpCode
];
} catch (Exception $e) {
error_log('Email exception: ' . $e->getMessage());
return [
'success' => false,
'error' => 'Email exception',
'details' => $e->getMessage()
];
}
}
/**
* Send email via SMTP
*/
private function sendViaSMTP($to, $subject, $text) {
try {
$from = $this->config['from'];
$host = $this->config['smtp_host'];
$port = $this->config['smtp_port'];
$username = $this->config['smtp_username'];
$password = $this->config['smtp_password'];
// Build email message
$headers = "From: {$from}\r\n";
$headers .= "Reply-To: {$from}\r\n";
$headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
// Create SMTP connection
$socket = fsockopen($host, $port, $errno, $errstr, 10);
if (!$socket) {
error_log('SMTP connection failed: ' . $errstr);
return [
'success' => false,
'error' => 'SMTP connection failed',
'details' => $errstr
];
}
// SMTP conversation
$this->smtpCommand($socket, null, 220); // Wait for greeting
$this->smtpCommand($socket, "EHLO " . $host, 250);
$this->smtpCommand($socket, "AUTH LOGIN", 334);
$this->smtpCommand($socket, base64_encode($username), 334);
$this->smtpCommand($socket, base64_encode($password), 235);
$this->smtpCommand($socket, "MAIL FROM: <{$from}>", 250);
$this->smtpCommand($socket, "RCPT TO: <{$to}>", 250);
$this->smtpCommand($socket, "DATA", 354);
// Send email data
$message = "Subject: {$subject}\r\n";
$message .= $headers;
$message .= "\r\n";
$message .= $text . "\r\n";
$message .= ".\r\n";
$this->smtpCommand($socket, $message, 250);
$this->smtpCommand($socket, "QUIT", 221);
fclose($socket);
error_log('Email sent via SMTP to ' . $to);
return [
'success' => true,
'method' => 'smtp'
];
} catch (Exception $e) {
error_log('SMTP exception: ' . $e->getMessage());
return [
'success' => false,
'error' => 'SMTP exception',
'details' => $e->getMessage()
];
}
}
/**
* Send SMTP command and check response
*/
private function smtpCommand($socket, $command, $expectedCode) {
if ($command !== null) {
fwrite($socket, $command . "\r\n");
}
$response = '';
while ($line = fgets($socket, 515)) {
$response .= $line;
if (substr($line, 3, 1) === ' ') {
break;
}
}
$code = intval(substr($response, 0, 3));
if ($code !== $expectedCode) {
throw new Exception("SMTP Error: Expected {$expectedCode}, got {$code}. Response: {$response}");
}
return $response;
}
/**
* Send process started notification
*/
public function notifyStarted($userEmail, $filename) {
$subject = 'Regional Hotfolder - Started';
$text = "Document: $filename has been picked up for processing.";
return $this->send($userEmail, $subject, $text);
}
/**
* Send process completed notification
*/
public function notifyCompleted($userEmail, $filename, $outputCount) {
$subject = 'Regional Hotfolder - Completed';
$text = "Document: $filename has completed processing.\n\n";
$text .= "Generated $outputCount regional CSV files.\n";
$text .= "Files should appear in OMG within 5 minutes.";
return $this->send($userEmail, $subject, $text);
}
/**
* Send error notification
*/
public function notifyError($userEmail, $filename, $errorMessage) {
$subject = 'Error - Regional Hotfolder';
$text = "An error occurred while processing: $filename\n\n";
$text .= "Error: $errorMessage\n\n";
$text .= "Please check the file and try again.";
return $this->send($userEmail, $subject, $text);
}
}