How to send attachments with mail in php
To send attachments with mail in PHP, you can use the mail()
function or a PHP mail library such as PHPMailer. Here are some examples:
Using the mail()
function:
<?php
$to = '[email protected]';
$subject = 'Test email with attachment';
$message = 'This is a test email with an attachment.';
// Set the attachment
$attachment = 'path/to/attachment.txt';
// Set the headers
$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 the message body.\r\n\r\n";
$message_body.= "--This is the boundary string\r\n";
$message_body.= "Content-Type: text/plain\r\n\r\n";
$message_body.= $message. "\r\n\r\n";
$message_body.= "--This is the boundary string\r\n";
$message_body.= "Content-Type: application/octet-stream; name=\"". $attachment. "\"\r\n";
$message_body.= "Content-Disposition: attachment; filename=\"". $attachment. "\"\r\n\r\n";
$message_body.= file_get_contents($attachment);
// Send the email
mail($to, $subject, $headers, $message_body);
?>
Using PHPMailer:
<?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.';
// Add the attachment
$mail->addAttachment('path/to/attachment.txt', 'text/plain', 'attachment', 'attachment.txt');
if (!$mail->send()) {
echo 'Error: '. $mail->ErrorInfo;
} else {
echo 'Email sent successfully!';
}
?>
In both examples, you need to replace the placeholders with your actual email settings and attachment path.
Note: The mail()
function is a built-in PHP function, but it has some limitations and may not work well with all email providers. PHPMailer is a more powerful and flexible library that can help you send emails with attachments and other features.