0
0
mirror of https://github.com/PHPMailer/PHPMailer.git synced 2024-09-20 01:52:15 +02:00
PHPMailer/examples/send_file_upload.phps

60 lines
2.0 KiB
Plaintext
Raw Normal View History

2014-12-24 10:40:13 +01:00
<?php
2014-12-24 10:40:13 +01:00
/**
* PHPMailer simple file upload and send example.
2014-12-24 10:40:13 +01:00
*/
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
2020-10-29 15:33:52 +01:00
require '../vendor/autoload.php';
2014-12-24 10:40:13 +01:00
$msg = '';
if (array_key_exists('userfile', $_FILES)) {
// First handle the upload
// Don't trust provided filename - same goes for MIME types
// See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
// Extract an extension from the provided filename
$ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
// Define a safe location to move the uploaded file to, preserving the extension
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'])) . '.' . $ext;
2014-12-24 10:40:13 +01:00
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// Upload handled successfully
// Now create a message
$mail = new PHPMailer();
2014-12-24 10:40:13 +01:00
$mail->setFrom('from@example.com', 'First Last');
$mail->addAddress('whoto@example.com', 'John Doe');
$mail->Subject = 'PHPMailer file sender';
2017-01-05 13:06:20 +01:00
$mail->Body = 'My message body';
2014-12-24 10:40:13 +01:00
// Attach the uploaded file
if (!$mail->addAttachment($uploadfile, 'My uploaded file')) {
$msg .= 'Failed to attach file ' . $_FILES['userfile']['name'];
}
2014-12-24 10:40:13 +01:00
if (!$mail->send()) {
$msg .= 'Mailer Error: ' . $mail->ErrorInfo;
2014-12-24 10:40:13 +01:00
} else {
2019-10-08 13:35:03 +02:00
$msg .= 'Message sent!';
2014-12-24 10:40:13 +01:00
}
} else {
2016-03-29 10:05:36 +02:00
$msg .= 'Failed to move file to ' . $uploadfile;
2014-12-24 10:40:13 +01:00
}
}
?>
<!DOCTYPE html>
<html lang="en">
2014-12-24 10:40:13 +01:00
<head>
2016-03-29 10:05:36 +02:00
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
2014-12-24 10:40:13 +01:00
<title>PHPMailer Upload</title>
</head>
<body>
<?php if (empty($msg)) { ?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000"> Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
<?php } else {
2020-08-04 08:51:55 +02:00
echo htmlspecialchars($msg);
2014-12-24 10:40:13 +01:00
} ?>
</body>
</html>