Attach an image and send mail using php
To attach an image and send a mail using PHP, you can use the mail()
function and the mime_content_type()
function to specify the type of the attachment. Here is an example:
<?php
// Set the recipient's email address
$to = '[email protected]';
// Set the subject of the email
$subject = 'Test Email with Attachment';
// Set the message body
$message = 'This is a test email with an attachment.';
// Set the path to the image file
$image_path = 'path/to/image.jpg';
// Set the name of the image file
$image_name = 'image.jpg';
// Open the image file
$image = fopen($image_path, 'rb');
// Read the image file
$image_data = fread($image, filesize($image_path));
// Close the image file
fclose($image);
// Set the headers for the email
$headers = 'From: [email protected]'. "\r\n".
'Reply-To: [email protected]'. "\r\n".
'MIME-Version: 1.0'. "\r\n".
'Content-Type: multipart/mixed; boundary="This is the boundary string"';
// Set the message body
$message_body = "This is a test email with an attachment.\r\n\r\n";
$message_body.= "--This is the boundary string\r\n";
$message_body.= "Content-Type: image/jpeg\r\n";
$message_body.= "Content-Disposition: attachment; filename=\"$image_name\"\r\n\r\n";
$message_body.= $image_data;
// Send the email
mail($to, $subject, $message_body, $headers);
?>
This code will send an email with the specified subject, message body, and attachment. The attachment is specified using the Content-Disposition
header and the Content-Type
header is set to image/jpeg
to indicate that the attachment is an image.
You can also use the PHPMailer
library which is a popular and easy to use library for sending emails in PHP. Here is an example of how you can use it to send an email with an attachment:
<?php
require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'username';
$mail->Password = 'password';
$mail->setFrom('[email protected]', 'Sender Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email with Attachment';
$mail->Body = 'This is a test email with an attachment.';
$mail->addAttachment('path/to/image.jpg', 'image/jpeg', 'attachment', 'image.jpg');
if (!$mail->send()) {
echo 'Error sending email: '. $mail->ErrorInfo;
} else {
echo 'Email sent successfully!';
}
?>
This code will send an email with the specified subject, message body, and attachment using the PHPMailer
library. The attachment is specified using the addAttachment()
method and the Content-Type
header is set to image/jpeg
to indicate that the attachment is an image.