How to send attachment mail in php
To send an email with an attachment in PHP, you can use the mail()
function or a PHP email library such as PHPMailer. Here's an example of how to do it using the mail()
function:
<?php
// Define the email details
$to = '[email protected]';
$subject = 'Email with attachment';
$message = 'This is the email body';
// Define the attachment details
$attachment = 'path/to/attachment.txt';
// Define the email 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"';
// Define the email body
$body = "This is the email body\r\n\r\n";
$body.= "--This is the boundary string\r\n";
$body.= "Content-Type: text/plain\r\n\r\n";
$body.= $message. "\r\n\r\n";
$body.= "--This is the boundary string\r\n";
$body.= "Content-Type: application/octet-stream; name=\"". basename($attachment). "\"\r\n";
$body.= "Content-Disposition: attachment; filename=\"". basename($attachment). "\"\r\n\r\n";
$body.= file_get_contents($attachment);
// Send the email
mail($to, $subject, $headers, $body);
?>
In this example, the email body is defined as a multipart message with a text/plain part and an attachment part. The attachment part is defined using the Content-Type
and Content-Disposition
headers, and the attachment data is read using the file_get_contents()
function.
Alternatively, you can use a PHP email library such as PHPMailer to send the email. Here's an example of how to do it using PHPMailer:
<?php
require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';
// Create a new PHPMailer instance
$mail = new PHPMailer\PHPMailer\PHPMailer();
// Set the email details
$mail->setFrom('[email protected]', 'Sender Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Email with attachment';
$mail->Body = 'This is the email body';
// Add the attachment
$mail->addAttachment('path/to/attachment.txt', 'text/plain', 'attachment', 'attachment.txt');
// Set the SMTP server
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'username';
$mail->Password = 'password';
// Send the email
if (!$mail->send()) {
echo 'Error: '. $mail->ErrorInfo;
} else {
echo 'Email sent successfully';
}
?>
In this example, the PHPMailer instance is created and the email details are set using the setFrom()
, addAddress()
, Subject
, and Body
methods. The attachment is added using the addAttachment()
method, and the SMTP server is set using the isSMTP()
, Host
, SMTPAuth
, Username
, and Password
methods. Finally, the email is sent using the send()
method, and an error message is displayed if the email is not sent successfully.