I am trying to send an image file from web forms to email, but it keeps sending an empty attachment. I have tried so many things, from changing emails to see if gmail is the problem, but it's all the same no matter what I try. Below is my code so far.
$tmpName = $_FILES['dl_image']['tmp_name'];
$fileType = $_FILES['dl_image']['type'];
$fileName = $_FILES['dl_image']['name'];
$size = $_FILES['dl_image']['size'];
if (file($tmpName))
{
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file, $size);
fclose($file);
/* Encoding file data */
$encoded_content = chunk_split(base64_encode(file_get_contents($data)));
$boundary = md5(date('r', time())); // define boundary with a md5 hashed value
$headers = "MIME-Version: 1.0
"; // Defining the MIME version
$headers .= "Content-Type: multipart/mixed;
"; // Defining Content-Type
$headers .= "boundary = $boundary
"; //Defining the Boundary
$body .= "--$boundary
";
$body .="Content-Type: $fileType; name=".$fileName."
";
$body .="Content-Disposition: attachment; filename=".$fileName."
";
$body .="Content-Transfer-Encoding: base64
";
$body .="X-Attachment-Id: ".rand(1000, 99999)."
";
$body .= $encoded_content; // Attaching the encoded file with email
$sentMailResult = mail($receiver, $subject, $body, $headers);
if($sentMailResult )
{
echo "File Sent Successfully.";
unlink($fileName); // delete the file after attachment sent.
}
else
{
die("Sorry but the email could not be sent. Please go back and try again!");
}
}
And also below is my html code. I was thinking may the problem could be from the html code, but all attachment attributes parse correctly.
<div class="file-upload">
<button class="file-upload-btn" type="button" onclick="$('.file-upload-input').trigger( 'click' )">Add Image</button>
<div class="image-upload-wrap">
<input class="file-upload-input" type="file" name="dl_image" onchange="readURL(this);" accept="image/*" />
<div class="drag-text">
<h3>Drag and drop a file or select add Image</h3>
</div>
</div>
<div class="file-upload-content">
<img class="file-upload-image" src="#" alt="your image" />
<div class="image-title-wrap">
<button type="button" onclick="removeUpload()" class="remove-image">Remove <span class="image-title">Uploaded Image</span></button>
</div>
</div>
</div>
question from:
https://stackoverflow.com/questions/65886103/sending-an-image-to-email-from-web-forms-using-php 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…