Php code put file contents to email
Here is an example of PHP code that sends an email with the contents of a file attached:
<?php
// Set the email variables
$to = '[email protected]';
$subject = 'File Attachment';
$from = '[email protected]';
// Set the file path and name
$file_path = 'path/to/file.txt';
$file_name = 'file.txt';
// Read the file contents
$file_contents = file_get_contents($file_path);
// Set the email headers
$headers = array(
'From: '. $from,
'To: '. $to,
'Subject: '. $subject,
'MIME-Version: 1.0',
'Content-Type: text/plain'
);
// Set the email body
$body = 'This is the email body.';
// Attach the file
$attachment = chunk_split(base64_encode(file_get_contents($file_path)));
// Set the email message
$message = "This is a multi-part message in MIME format.\n\n".
"This is the text part of the message.\n\n".
"--". $boundary. "\n".
"Content-Type: application/octet-stream; name=\"". $file_name. "\"\n".
"Content-Transfer-Encoding: base64\n".
"Content-Disposition: attachment; filename=\"". $file_name. "\"\n\n".
$attachment. "\n\n".
"--". $boundary. "--";
// Send the email
mail($to, $subject, $body, $headers);
?>
This code uses the mail()
function to send the email, and the file_get_contents()
function to read the contents of the file. The file contents are then encoded using base64 and attached to the email using the Content-Disposition
header.
You can also use the PHPMailer
library which is a popular and easy to use library for sending emails in PHP. Here is an example of how you can use it:
<?php
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'File Attachment';
$mail->Body = 'This is the email body.';
$file_path = 'path/to/file.txt';
$file_name = 'file.txt';
$mail->addAttachment($file_path, $file_name);
$mail->send();
?>
This code uses the PHPMailer
library to send the email, and the addAttachment()
method to attach the file to the email.
Make sure to replace the placeholders with your actual email address, password, and file path.