Send Email with Attachment in PHP
Sending emails from the script is a very useful functionality in the web application. Most of the websites used the email sending feature to send notifications to the user. If your web application developed with PHP or uses PHP, it’s very easy to send email from the script using PHP.
PHP provides an easy way to send emails from the website. You can send text or HTML email with mail() function in PHP. But sometimes email functionality needs to be extended for sending an attachment with the mail. In this tutorial, we will show you how to send email with attachment in PHP.
In the example script, we will make it simple to send text or HTML email including any types of files as an attachment (like image, .doc, .docx, .pdf, .txt, etc.) using PHP.
Send HTML Email with Attachment
The PHP mail() function with some MIME type headers can be used to send email with attachment in PHP. In the following example code, MIME and Content-Type headers are used with mail() function to send email with attachment using PHP.
- $to – Recipient email address.
- $from – Sender email address.
- $fromName – Sender name.
- $subject – Subject of the email.
- $file – Relative path of the file that you want to attach with the email.
- $htmlContent – Body content of the email (Text or HTML).
The following script lets you send both types of messages (text or HTML) with an attachment file to the email.
// Recipient
$to = 'recipient@example.com';
// Sender
$from = 'sender@example.com';
$fromName = 'CodexWorld';
// Email subject
$subject = 'PHP Email with Attachment by CodexWorld';
// Attachment file
$file = "files/codexworld.pdf";
// Email body content
$htmlContent = 'PHP Email with Attachment by CodexWorld
This email is sent from the PHP script with attachment.
';
// Header for sender info
$headers = "From: $fromName"." .$from.">";
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x$semi_rand>x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"$mime_boundary>\"";
// Multipart boundary
$message = "--$mime_boundary>\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(!empty($file) > 0) <
if(is_file($file)) <
$message .= "--$mime_boundary>\n";
$fp = @fopen($file,"rb");
$data = @fread($fp,filesize($file));
@fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\n" .
"Content-Description: ".basename($file)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($file)."\"; size color: #007700">.filesize($file).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
>
>
$message .= "--$mime_boundary>--";
$returnpath = "-f" . $from;
// Send email
$mail = @mail($to, $subject, $message, $headers, $returnpath);
// Email sending status
echo $mail?"Email Sent Successfully!
":"Email sending failed.
";
?>
The example script allows you to send a single attachment to the email, to send an email with multiple attachments follow this tutorial – Send Email with Multiple Attachments in PHP
Sending Email to Multiple Recipients:
You can send email to multiple recipients at once with Cc and Bcc headers. Use the Cc and Bcc headers for sending email with attachment to multiple recipients in PHP.
$headers .= "\nCc: mail@example.com";
$headers .= "\nBcc: mail@example.com";
Conclusion
Here we have provided the easiest way to send email with attachment in PHP. You don’t need to include any library to send HTML email with attachments. Using the PHP default mail() function you can easily send email with pdf/image attachment.
Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request
If you have any questions about this script, submit it to our QA community — Ask Question
File attachments in php
I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:
Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)
Anyways, here is a fuller example than the sparce one in the documentation above:
foreach ( $_FILES [ «attachment» ][ «error» ] as $key => $error )
$tmp_name = $_FILES [ «attachment» ][ «tmp_name» ][ $key ];
if (! $tmp_name ) continue;
$name = basename ( $_FILES [ «attachment» ][ «name» ][ $key ]);
if ( $error == UPLOAD_ERR_OK )
if ( move_uploaded_file ( $tmp_name , «/tmp/» . $name ) )
$uploaded_array [] .= «Uploaded file ‘» . $name . «‘.
\n» ;
else
$errormsg .= «Could not move uploaded file ‘» . $tmp_name . «‘ to ‘» . $name . «‘
\n» ;
>
else $errormsg .= «Upload error. [» . $error . «] on file ‘» . $name . «‘
\n» ;
>
?>
Do not use Coreywelch or Daevid’s way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.
The following example form breaks their codes:
As the solution, you should use PSR-7 based zendframework/zend-diactoros.
use Psr \ Http \ Message \ UploadedFileInterface ;
use Zend \ Diactoros \ ServerRequestFactory ;
$request = ServerRequestFactory :: fromGlobals ();
if ( $request -> getMethod () !== ‘POST’ ) http_response_code ( 405 );
exit( ‘Use POST method.’ );
>
$uploaded_files = $request -> getUploadedFiles ();
if (
!isset( $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ]) ||
! $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ] instanceof UploadedFileInterface
) http_response_code ( 400 );
exit( ‘Invalid request body.’ );
>
$file = $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ];
if ( $file -> getError () !== UPLOAD_ERR_OK ) http_response_code ( 400 );
exit( ‘File uploading failed.’ );
>
$file -> moveTo ( ‘/path/to/new/file’ );
The documentation doesn’t have any details about how the HTML array feature formats the $_FILES array.
Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
Multi-files with HTML array feature —
Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)
(
[0] => application/msword
[1] => application/msword
) [tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)
The problem occurs when you have a form that uses both single file and HTML array feature. The array isn’t normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.
function normalize_files_array ( $files = [])
foreach( $files as $index => $file )
if (! is_array ( $file [ ‘name’ ])) $normalized_array [ $index ][] = $file ;
continue;
>
foreach( $file [ ‘name’ ] as $idx => $name ) $normalized_array [ $index ][ $idx ] = [
‘name’ => $name ,
‘type’ => $file [ ‘type’ ][ $idx ],
‘tmp_name’ => $file [ ‘tmp_name’ ][ $idx ],
‘error’ => $file [ ‘error’ ][ $idx ],
‘size’ => $file [ ‘size’ ][ $idx ]
];
>
?>
The following is the output from the above method.
Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
) [1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
How to attach file with feedback form in PHP ?
Feedback form is used to get the review from the user through mail services. Mailing is one of the server-side utilities that is required in most of the web servers today. In PHP, mail() is the built-in function that is used to send emails from PHP scripts either in a plain-text form or formatted HTML. You can also write a script to attach any files into your mail from send Attachment With Email article.
The PHP mail function has the following basic Syntax:
Attaching file in feedback form: To send an email with attachment as feedback, we need to use the multipart/mixed MIME type(set Content-type header to multipart/mixed) that specifies that mixed types will be included in the email. Moreover, we want to use a multipart/alternative MIME type to send both plain-text and HTML versions of the email. Text and attachment sections can be specified within boundaries. A boundary is started with two hyphens followed by a unique number that can not appear in the message part of the email. A PHP function md5() is used to create a 32 digit hexadecimal number to create a unique number. A final boundary denoting the email’s final section must also end with two hyphens.
To include an attachment to our message, we read the data from the specified file into a string, encode it with base64_encode() function for safer transmission, split it in smaller chunks with the chunk_split() function to make sure that it matches the MIME specifications and then include it as an attachment.
PHP | Send Attachment With Email
Sending an email is a very common activity in a web browser. For example, sending an email when a new user joins a network, sending a newsletter, sending greeting mail, or sending an invoice. We can use the built-in mail() function to send an email programmatically. This function needs three required arguments that hold the information about the recipient, the subject of the message and the message body. Along with these three required arguments, there are two more arguments which are optional. One of them is the header and the other one is parameters.
We have already discussed sending text-based emails in PHP in our previous article. In this article, we will see how we can send an email with attachments using the Mime-Versionmail() function.
When the mail() function is called PHP will attempt to send the mail immediately to the recipient then it will return true upon successful delivery of the mail and false if an error occurs.
Syntax:
bool mail( $to, $subject, $message, $headers, $parameters );
Here is the description of each parameter.
Name | Description | Required/Optional | Type |
---|---|---|---|
to | This contains the receiver or receivers of the particular email | Required | String |
subject | This contains the subject of the email. This parameter cannot contain any newline characters | Required | String |
message | This contains the message to be sent. Each line should be separated with an LF (\n). Lines should not exceed 70 characters (We will use wordwrap() function to achieve this.) | Required | String |
headers | This contains additional headers, like From, Cc, Mime Version, and Bcc. | Optional | String |
parameters | Specifies an additional parameter to the send mail program | Optional | String |
When we are sending mail through PHP, all content in the message will be treated as simple text only. If we put any HTML tag inside the message body, it will not be formatted as HTML syntax. HTML tag will be displayed as simple text.
To format any HTML tag according to HTML syntax, we can specify the MIME (Multipurpose Internet Mail Extension) version, content type and character set of the message body.
To send an attachment along with the email, we need to set the Content-type as mixed/multipart and we have to define the text and attachment sections within a Boundary.
Approach: Make sure you have a XAMPP server or WAMP server installed on your machine. In this article, we will be using the WAMP server.
Follow the steps given below:
Create an HTML form: Below is the HTML source code for the HTML form. In the HTML tag, we are using “enctype=’multipart/form-data” which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form.