Php email attachment

In PHP, you can send an email with an attachment using the mail() function or a PHP mail library such as PHPMailer. Here are some examples:

Using the mail() function

<?php
$to = '[email protected]';
$subject = 'Email with attachment';
$message = 'This is the email body';

// Set the attachment
$attachment = 'path/to/attachment.txt';

// Set the email headers
$headers = 'From: [email protected]'. "\r\n".
           'Content-Type: text/plain; charset=UTF-8'. "\r\n".
           'Content-Disposition: attachment; filename="'. $attachment. '"';

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

In this example, the mail() function is used to send an email with a text attachment. The Content-Disposition header is set to attachment to indicate that the attachment should be treated as a file attachment.

Using PHPMailer

<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'username';
$mail->Password = 'password';

$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');

$mail->send();
?>

In this example, the PHPMailer library is used to send an email with a text attachment. The addAttachment() method is used to add the attachment to the email.

Common issues

Security considerations