I would like to create a contact form, where the email is sent along with an auto-generated attachment file (.txt). The attachment should include all the values of the input fields present in the contact form (whether they are empty or not). Can this be done by using PHP mail()? My code now can only send the contact form contents as the email body:
<?php
define("WEBMASTER_EMAIL", 'info@email.com');
error_reporting (E_ALL);
if(!empty($_POST))
{
$_POST = array_map('trim', $_POST);
$name = htmlspecialchars($_POST['name']);
$email = $_POST['email'];
$subject = htmlspecialchars($_POST['subject']);
$message = htmlspecialchars($_POST['message']);
$error = array();
if(empty($name))
{
$error[] = 'Please enter your name';
}
if(empty($email))
{
$error[] = 'Please enter your e-mail';
}
elseif(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error[] = 'e-mail is incorrect';
}
if(empty($message) || empty($message{15}))
{
$error[] = "Please enter message more than 15 characters";
}
if(empty($error))
{
$body = '
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr><td>Name: </td><td> </td><td>'.$name.'</td><tr>
<tr><td> </td><td> </td><td> </td></tr>
<tr><td>Email: </td><td> </td><td>'.$email.'</td><tr>
<tr><td> </td><td> </td><td> </td></tr>
<tr><td>Subject: </td><td> </td><td>'.$subject.'</td><tr>
<tr><td> </td><td> </td><td> </td></tr>
<tr><td>Message: </td><td> </td><td>'.stripslashes($message).'</td><tr>
</table>
</body>
</html>
';
$mail = mail(WEBMASTER_EMAIL, 'Message sent from website', $body,
"MIME-Version: 1.0" . "\r\n"
."Content-type: text/html; charset=UTF-8" . "\r\n"
."From: ".$email." \r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
echo 'OK';
}
}
else
{
echo '<div class="notification_error">'.implode('<br />', $error).'</div>';
}
}
?>
To generate a file using the form values, see this example.
If You want to send an e-mail using php mail() with text and attachment, You have to mess a little bit with the headers. Add Content-Type: multipart/mixed;
to the headers, see example.