1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-10 13:12:50 +01:00
invoiceninja/app/Ninja/Mailers/Mailer.php
Hillel Coren 2dfc053cbc Bug fixes
2015-10-13 10:11:44 +03:00

85 lines
2.5 KiB
PHP

<?php namespace App\Ninja\Mailers;
use Exception;
use Mail;
use Utils;
use App\Models\Invoice;
class Mailer
{
public function sendTo($toEmail, $fromEmail, $fromName, $subject, $view, $data = [])
{
if (isset($_ENV['POSTMARK_API_TOKEN'])) {
$views = 'emails.'.$view.'_html';
} else {
$views = [
'emails.'.$view.'_html',
'emails.'.$view.'_text',
];
}
try {
$response = Mail::send($views, $data, function ($message) use ($toEmail, $fromEmail, $fromName, $subject, $data) {
$toEmail = strtolower($toEmail);
$replyEmail = $fromEmail;
$fromEmail = CONTACT_EMAIL;
$message->to($toEmail)
->from($fromEmail, $fromName)
->replyTo($replyEmail, $fromName)
->subject($subject);
// Attach the PDF to the email
if (!empty($data['pdfString']) && !empty($data['pdfFileName'])) {
$message->attachData($data['pdfString'], $data['pdfFileName']);
}
});
return $this->handleSuccess($response, $data);
} catch (Exception $exception) {
return $this->handleFailure($exception);
}
}
private function handleSuccess($response, $data)
{
if (isset($data['invitation'])) {
$invitation = $data['invitation'];
// Track the Postmark message id
if (isset($_ENV['POSTMARK_API_TOKEN']) && $response) {
$json = $response->json();
$invitation->message_id = $json['MessageID'];
}
$invitation->email_error = null;
$invitation->sent_date = \Carbon::now()->toDateTimeString();
$invitation->save();
}
return true;
}
private function handleFailure($exception)
{
if (isset($_ENV['POSTMARK_API_TOKEN'])) {
$response = $exception->getResponse()->getBody()->getContents();
$response = json_decode($response);
$emailError = nl2br($response->Message);
} else {
$emailError = $exception->getMessage();
}
Utils::logError("Email Error: $emailError");
if (isset($data['invitation'])) {
$invitation = $data['invitation'];
$invitation->email_error = $emailError;
$invitation->save();
}
return $emailError;
}
}