How to attachment in mail function of php
In PHP, you can attach files to an email using the mail()
function by specifying the file path and name in the Additional headers
section. Here's an example:
<?php
$to = '[email protected]';
$subject = 'File Attachment Example';
$message = 'This is a test email with an attachment.';
// Define the file path and name
$file_path = 'path/to/your/file.txt';
$file_name = 'file.txt';
// Set the content type and attachment headers
$headers = array(
'From' => '[email protected]',
'Subject' => $subject,
'Content-Type' => 'text/plain; charset=UTF-8',
'Content-Disposition' => 'attachment; filename="'. $file_name. '"'
);
// Add the file to the email
$mail = mail($to, $subject, $message, implode("\r\n", $headers), $file_path);
if ($mail) {
echo 'Email sent successfully!';
} else {
echo 'Error sending email.';
}
?>
In this example, we're attaching a file named file.txt
located at path/to/your/file.txt
. The Content-Disposition
header is set to attachment
to indicate that the file should be treated as an attachment, and the filename
parameter is set to the desired file name.
Note that the mail()
function returns a boolean value indicating whether the email was sent successfully. If the email is sent successfully, the function returns true
; otherwise, it returns false
.
Alternatively, you can use the mime_content_type()
function to specify the MIME type of the attachment, and the base64_encode()
function to encode the file contents:
<?php
$to = '[email protected]';
$subject = 'File Attachment Example';
$message = 'This is a test email with an attachment.';
// Define the file path and name
$file_path = 'path/to/your/file.txt';
$file_name = 'file.txt';
// Set the content type and attachment headers
$headers = array(
'From' => '[email protected]',
'Subject' => $subject,
'Content-Type' => 'multipart/mixed; boundary="----------"',
'Content-Disposition' => 'attachment; filename="'. $file_name. '"'
);
// Read the file contents
$file_contents = file_get_contents($file_path);
// Encode the file contents using base64
$file_encoded = base64_encode($file_contents);
// Add the file to the email
$mail = mail($to, $subject, $message, implode("\r\n", $headers), $file_encoded);
if ($mail) {
echo 'Email sent successfully!';
} else {
echo 'Error sending email.';
}
?>
In this example, we're using the mime_content_type()
function to specify the MIME type of the attachment (in this case, text/plain
), and the base64_encode()
function to encode the file contents. The Content-Type
header is set to multipart/mixed
to indicate that the email contains multiple parts, including the attachment. The boundary
parameter is set to a unique string to separate the different parts of the email.
Note that the mail()
function may not work as expected if you're using a web server that has a strict security policy, such as a shared hosting environment. In such cases, you may need to use a third-party library or service to send emails with attachments.