How to add attachments in mail using smtp php

To add attachments in a mail using SMTP in PHP, you can use the mail() function or a PHP mail library like PHPMailer. Here's an example of how to do it using PHPMailer:

Step 1: Install PHPMailer

You can install PHPMailer using Composer:

composer require phpmailer/phpmailer

Step 2: Configure PHPMailer

Create a new PHP file and include the PHPMailer library:

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

Configure the SMTP settings:

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'your_smtp_host';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$mail->Port = 587; // or 25, 465, etc.

Step 3: Set the mail properties

Set the mail properties, such as the sender, recipient, subject, and body:

$mail->setFrom('your_from_email', 'Your Name');
$mail->addAddress('recipient_email');
$mail->Subject = 'Test Email with Attachment';
$mail->Body = 'This is a test email with an attachment.';

Step 4: Add the attachment

Add the attachment using the addAttachment() method:

$mail->addAttachment('path/to/attachment/file.pdf', 'application/pdf');

Step 5: Send the mail

Send the mail using the send() method:

$mail->send();

Here's the complete code:

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

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'your_smtp_host';
$mail->SMTPAuth = true;
$mail->Username = 'your_smtp_username';
$mail->Password = 'your_smtp_password';
$mail->Port = 587; // or 25, 465, etc.

$mail->setFrom('your_from_email', 'Your Name');
$mail->addAddress('recipient_email');
$mail->Subject = 'Test Email with Attachment';
$mail->Body = 'This is a test email with an attachment.';

$mail->addAttachment('path/to/attachment/file.pdf', 'application/pdf');

$mail->send();

Make sure to replace the placeholders with your actual SMTP settings and attachment path.

Using the mail() function

If you prefer to use the mail() function, you can use the following code:

<?php
$to = 'recipient_email';
$subject = 'Test Email with Attachment';
$body = 'This is a test email with an attachment.';

$attachment = 'path/to/attachment/file.pdf';

$headers = 'From: your_from_email'. "\r\n".
    'Reply-To: your_from_email'. "\r\n".
    'MIME-Version: 1.0'. "\r\n".
    'Content-Type: multipart/mixed; boundary="===============1234567890=="';

$message = "This is a test email with an attachment.\r\n\r\n".
    '--===============1234567890==--'. "\r\n".
    'Content-Type: application/pdf'. "\r\n".
    'Content-Disposition: attachment; filename="file.pdf"'. "\r\n".
    'Content-Transfer-Encoding: base64'. "\r\n".
    chunk_split(base64_encode(file_get_contents($attachment)));

mail($to, $subject, $body, $headers, $message);

Make sure to replace the placeholders with your actual email address, subject, body, and attachment path.