Php email attachments

In PHP, you can send an email with attachments using the mail() function or a PHP mail library such as PHPMailer. Here's an example of how to send an email with attachments 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 file name
$filename = 'attachment.txt';

// Set the content type
$content_type = 'text/plain';

// Set the boundary
$boundary = '-----boundary';

// Set the headers
$headers = "MIME-Version: 1.0\r\n";
$headers.= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";

// Set the message body
$message_body = "This is a test email with an attachment.\r\n\r\n";
$message_body.= "--$boundary\r\n";
$message_body.= "Content-Type: $content_type; name=\"$filename\"\r\n";
$message_body.= "Content-Disposition: attachment; filename=\"$filename\"\r\n";
$message_body.= "Content-Transfer-Encoding: base64\r\n\r\n";
$message_body.= chunk_split(base64_encode(file_get_contents($attachment)), 76, "\r\n ");
$message_body.= "--$boundary--";

// Send the email
mail($to, $subject, $message_body, $headers);
?>

In this example, we're sending an email with a text file attachment. We set the attachment path, file name, content type, and boundary. We then set the headers and message body, which includes the attachment.

If you're using PHPMailer, you can send an email with attachments like this:

<?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', 'attachment.txt', 'text/plain');

if (!$mail->send()) {
    echo 'Error: '. $mail->ErrorInfo;
} else {
    echo 'Email sent successfully!';
}
?>

In this example, we're using PHPMailer to send an email with a text file attachment. We set the SMTP server, authentication, and email details. We then add the attachment using the addAttachment() method.

Remember to replace the placeholders with your actual email details and attachment path.