自动生成联系表单中的内容附件并通过电子邮件发送

时间:2012-10-17 08:44:32

标签: php email email-attachments auto-generate

我想创建一个联系表单,其中电子邮件与自动生成的附件文件(.txt)一起发送。附件应包括联系表单中存在的输入字段的所有值(无论它们是否为空)。这可以通过使用PHP mail()来完成吗?我的代码现在只能将联系表单内容作为电子邮件正文发送:

<?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>&nbsp;</td><td>'.$name.'</td><tr>
<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td>Email: </td><td>&nbsp;</td><td>'.$email.'</td><tr>
<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td>Subject: </td><td>&nbsp;</td><td>'.$subject.'</td><tr>
<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td>Message: </td><td>&nbsp;</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>'; 
}
}  
?>

1 个答案:

答案 0 :(得分:0)

要使用表单值生成文件,请参阅此example

如果您想使用带有文本和附件的php mail()发送电子邮件,您必须使用标题弄乱一点。将Content-Type: multipart/mixed;添加到标题中,请参阅example