simple mail()将从mysql生成一个获取的报告

时间:2014-06-27 15:57:17

标签: php mysql email

使用简单的mail()函数在php中发送邮件。

我想发送邮件,该邮件将生成从mysql数据库中获取的报告,但mail()需要4个参数mail($to,$subject,$message,$from)我无法生成$message,因为它将保留具有获取值和特定格式的邮件正文。

我的script.php生成报告: -

<?php
$to  = 'abc@gmail.com' . ', ';
$subject = 'Test Mail';

$query=mysql_query("SELECT * from table_name ");

echo'<html>
<head>
<title>Testing</title>
</head>
<h1>Test User</h1>
<table border="1" cellspacing="1">

<tr>
<th>id</th>
<th>user</th>
<th>phoneCount</th>';

while($row = mysql_fetch_array($query))
 {
echo  "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['user'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "</tr>";
}
echo "</table>";      
echo "</html>";

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// More headers
$headers .= 'From: <from@example.com>' . "\r\n";
mail($to, $subject, $msg, $headers);
?>

因为我得到了$ to,$ subject,$ headers的值但$ msg正在创建问题。我可以用这种格式发送邮件。我无法弄清楚如何获取邮件正文$ msg将生成报告

2 个答案:

答案 0 :(得分:1)

嗯,这是最简单的形式,而不是回显你要将内容分配给变量的内容。

你有几个选择:

1)变量连接

$message = '<p>Line 1</p>';
$message .= '<p>' . $line2 . '</p>';
$message .= '<p>Line 3</p>';

$ message的内容将是:

<p>Line 1</p><p>Line 2</p><p>Line 3</p>

2)输出缓冲

ob_start(); // http://www.php.net/manual/en/function.ob-start.php

echo '<p>Line 1</p>';
echo '<p>' . $line2 . '</p>';
echo '<p>Line 3</p>';

$message = ob_get_clean(); // http://www.php.net/manual/en/function.ob-get-clean.php

3)Heredoc语法(这种方法可能会变得棘手我现在不推荐它)

$message = <<<EOT

<p>Line 1</p>
<p>$line2</p>
<p>Line 3</p>

EOT;

这三种方法中的每一种都可以让您将内容分配到$ message中。

但默认情况下,邮件只会发送纯文本电子邮件。如果你想发送HTML电子邮件,你需要设置特定的标题,理想情况下你应该设置多部分边界等。我可能建议使用像Zend这样的库,你可以包括零碎的。如果失败,这是一个基本的例子:http://css-tricks.com/sending-nice-html-email-with-php/

希望有所帮助。

答案 1 :(得分:0)

更改代码的这一部分:

echo'<html>
<head>
<title>Testing</title>
</head>
<h1>Test User</h1>
<table border="1" cellspacing="1">

<tr>
<th>id</th>
<th>user</th>
<th>phoneCount</th>';

while($row = mysql_fetch_array($query))
 {
echo  "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['user'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "</tr>";
}
echo "</table>";      
echo "</html>";

如下所示:

$msg = '<html>
<head>
<title>Testing</title>
</head>
<h1>Test User</h1>
<table border="1" cellspacing="1">';

$msg = $msg . "<tr>";
$msg = $msg . "<th>id</th>";
$msg = $msg . "<th>user</th>";
$msg = $msg . "<th>phoneCount</th>";
while($row = mysql_fetch_array($query))
 {
$msg = $msg . "<tr>";
$msg = $msg ."<td>" . $row['id'] . "</td>";
$msg = $msg ."<td>" . $row['user'] . "</td>";
$msg = $msg ."<td>" . $row['phone'] . "</td>";
$msg = $msg ."</tr>";
}
$msg = $msg . "</table>";      
$msg = $msg . "</html>";