rosavox/lib/alveolata/email/implementation-legacy/functions.php
2025-05-23 07:33:29 +00:00

96 lines
2.7 KiB
PHP

<?php
namespace alveolata\email\implementations\legacy;
require_once(DIR_ALVEOLATA . '/email/base.php');
/**
* @todo use credentials
* @author Christian Fraß <frass@greenscale.de>
*/
function send(
\alveolata\email\struct_credentials $credentials,
\alveolata\email\struct_data $data
) : void
{
// constants
$separator = \md5(\time());
// helpers
$headerEntry = function ($key, $value, $args = []) {
return \sprintf(
"%s: %s%s\r\n",
$key,
$value,
\implode(
'',
\array_map(
fn($x) => \sprintf('; %s=%s', $x, $args[$x]),
\array_keys($args)
)
)
);
};
$separatorEntry = function ($final) use ($separator) {
return (
$final
? \sprintf("--%s--\r\n", $separator)
: \sprintf("--%s\r\n", $separator)
);
};
$textEntry = function ($content) {
return \sprintf("\r\n%s\r\n", $content);
};
// vars
$message = '';
$additional_headers = '';
$additional_headers .= $headerEntry('To', \implode(',', $data->to));
$additional_headers .= $headerEntry('Subject', $data->subject);
if (! empty($data->from)) {
$additional_headers .= $headerEntry('From', $data->from);
}
if (! empty($data->reply_to)) {
$additional_headers .= $headerEntry('Reply-To', $data->reply_to);
}
if (! empty($data->cc)) {
$additional_headers .= $headerEntry('Cc', \implode(',', $data->cc));
}
if (! empty($data->bcc)) {
$additional_headers .= $headerEntry('Bcc', \implode(',', $data->bcc));
}
if (empty($data->attachments)) {
$additional_headers .= $headerEntry('Content-Type', 'text/plain', ['charset' => 'utf-8']);
$message .= $textEntry(\wordwrap($data->body_plain));
}
else {
$additional_headers .= $headerEntry('MIME-Version', '1.0');
$additional_headers .= $headerEntry('Content-Type', 'multipart/mixed', ['boundary' => $separator]);
$message .= $separatorEntry(false);
$message .= $headerEntry('Content-Type', 'text/plain', ['charset' => 'utf-8']);
$message .= $headerEntry('Content-Transfer-Encoding', '7bit');
$message .= $textEntry(\wordwrap($data->body_plain));
foreach ($data->attachments as $attachment) {
$message .= $separatorEntry(false);
$message .= $headerEntry('Content-Transfer-Encoding', 'base64');
$message .= $headerEntry('Content-Type', $attachment['mime'] ?? 'application/octet-stream');
$message .= $headerEntry('Content-Disposition', 'attachment', ['filename' => ($attachment['name'] ?? \basename($attachment['path']))]);
$message .= $textEntry(\chunk_split(\base64_encode(\file_get_contents($attachment['path']))));
}
$message .= $separatorEntry(true);
}
// exec
$successful = \mail(
\implode(',', $data->to),
$data->subject,
$message,
$additional_headers
);
if (! $successful) {
throw (new \Exception(\sprintf('mail_could_not_be_sent')));
}
}
?>