Методы загрузки изображения и отправки его по электронной почте с помощью PHP

Чтобы загрузить изображение и отправить его по электронной почте с помощью PHP, вы можете выбрать один из нескольких способов. Вот три часто используемых метода с примерами кода:

Метод 1: использование PHPMailer
PHPMailer — популярная библиотека, упрощающая отправку электронной почты на PHP. Вы можете использовать его, чтобы прикрепить загруженное изображение и отправить его по электронной почте.

<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
// Get the uploaded image file
$uploadedFile = $_FILES['image']['tmp_name'];
$filename = $_FILES['image']['name'];
// Set up PHPMailer
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@example.com';
$mail->Password = 'your_email_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Set up email content
$mail->setFrom('your_email@example.com', 'Your Name');
$mail->addAddress('recipient@example.com');
$mail->Subject = 'Image Upload';
$mail->Body = 'Please find the uploaded image attached.';
$mail->addAttachment($uploadedFile, $filename);
// Send the email
if ($mail->send()) {
    echo 'Email sent successfully!';
} else {
    echo 'Email could not be sent.';
}
?>

Метод 2: использование встроенной функции mail.
Вы также можете использовать встроенную функцию mailв PHP для отправки электронного письма с загруженным изображением. в виде вложения. Однако этот метод требует дополнительной обработки заголовков электронной почты и кодирования данных изображения.

<?php
// Get the uploaded image file
$uploadedFile = $_FILES['image']['tmp_name'];
$filename = $_FILES['image']['name'];
// Email parameters
$to = 'recipient@example.com';
$from = 'your_email@example.com';
$subject = 'Image Upload';
$message = 'Please find the uploaded image attached.';
$fileContent = file_get_contents($uploadedFile);
$fileContentEncoded = chunk_split(base64_encode($fileContent));
// Email headers
$boundary = md5(time());
$headers = "From: $from\r\n"
    . "MIME-Version: 1.0\r\n"
    . "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n"
    . "X-Mailer: PHP/" . phpversion();
// Email body
$body = "--$boundary\r\n"
    . "Content-Type: text/plain; charset=ISO-8859-1\r\n"
    . "Content-Transfer-Encoding: 7bit\r\n\r\n"
    . "$message\r\n\r\n"
    . "--$boundary\r\n"
    . "Content-Type: application/octet-stream; name=\"$filename\"\r\n"
    . "Content-Transfer-Encoding: base64\r\n"
    . "Content-Disposition: attachment; filename=\"$filename\"\r\n\r\n"
    . "$fileContentEncoded\r\n"
    . "--$boundary--";
// Send the email
if (mail($to, $subject, $body, $headers)) {
    echo 'Email sent successfully!';
} else {
    echo 'Email could not be sent.';
}
?>

Метод 3: использование сторонней библиотеки (Swift Mailer)
Swift Mailer — еще одна популярная библиотека, которая упрощает отправку электронной почты на PHP. Вот пример использования Swift Mailer для отправки электронного письма с загруженным изображением в качестве вложения:

<?php
require 'swiftmailer/vendor/autoload.php';
// Get the uploaded image file
$uploadedFile = $_FILES['image']['tmp_name'];
$filename = $_FILES['image']['name'];
// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.example.com', 587, 'tls'))
    ->setUsername('your_email@example.com')
    ->setPassword('your_email_password');
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
// Create a message
$message = (new Swift_Message('Image Upload'))
    ->setFrom(['your_email@example.com' => 'Your Name'])
    ->setTo(['recipient@example.com'])
    ->setBody('Please find the uploaded image attached.')
    ->attach(new Swift_Attachment($uploadedFile, $filename));
// Send the message
if ($mailer->send($message)) {
    echo 'Email sent successfully!';
} else {
    echo 'Email could not be sent.';
}
?>