Hi everyone, welcome to pinepl today we are going to show you how to send email with attachments in php, in this tutorial we will show you easy method to send attachment in email using php so let’s start.
//Send Email With Attachment in PHP - Veewom
<?php
//receiver of the email
$to = 'username@example.com';
//subject of the email
$subject = 'Send email with attachment';
$random_hash = md5(date('r', time()));
//define the headers.
$headers = "From: Veewom Reply-To: noreply@veewom.com";
//mime type specification
$headers .= "rnContent-Type: multipart/mixed; boundary="PHP-mixed-".$random_hash.""";
//read the atachment file contents into a string,
//encode the contents with MIME base64,
//and split the contents into smaller chunks using given below function
$attachments = chunk_split(base64_encode(file_get_contents('file.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
Hello!!!
This is simple text email message.
--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<h2>Hello!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
--PHP-alt-<?php echo $random_hash; ?>--
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="file.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--
<?php
//copy current buffer contents into $message
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
We hope this article helped you learn how to Send Email With Attachments in PHP. You may also want to see – How To Change The Default WordPress Email Address.
If you liked this article, then please share to social networking site. You can also find us on Twitter,Facebook and Instagram.