我对如何使用foreach感到有点困惑。我在上面读了一些互联网的东西,我有点理解它是如何工作的,但我并不完全理解它。我想我可以使用foreach创建一个PHP大规模电子邮件程序,它将空白的抄送发送到电子邮件地址,并通过主题中的名称来对待客户(亲爱的,迈克尔这是您的电子邮件)。我已经想出如何从我的数据库中检索名称和电子邮件到变量,我知道如何发送电子邮件,但我不知道如何一次发送多封电子邮件并关联名称和电子邮件地址。
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "MichaelBerna.db.10339998.hostedresource.com";
$username = "MichaelBerna";
$dbname = "MichaelBerna";
//These variable values need to be changed by you before deploying
$password = "********";
$usertable = "subscribers";
$yourfield = "name";
$yourfield1 = "email";
//Connecting to your database
$link = mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result)
{
while($row = mysql_fetch_array($result))
{
$name = $row["$yourfield"];
$email = $row["$yourfield1"];
echo "Name: $name<br>";
echo "Email: $email<br>";
//mysqli_free_result($result);
//mysqli_close($link);
}
}
?>
这是我的电子邮件代码:
<?php
require_once '../PHPMailer_5.2.2/class.phpmailer.php';
$name = $_POST['name'] ;
$email = $_POST['email'] ;
//$file = $_POST['file'] ; // I'm going to later add a file later to be attached in email from database
$body = "Hey $name thank you for continuing to be a valued customer! This month's story is included in this email asa an attachment.";
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
try
{
$mail->AddAddress($email, $name);
$mail->SetFrom('admins_email@yahoo.com', 'Site Admin');
$mail->AddReplyTo('admins_email@yahoo.com', 'Site Admin');
$mail->Subject = "Dear $name Your monthly subscription has arrived!";
$mail->Body = $body;
if ($_FILES['file']['size'])
{
$mail->AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']);// attachment
}
$mail->Send();
echo "Email Sent Successfully</p>\n";
}
catch (phpmailerException $e)
{
echo $e->errorMessage(); //Pretty error messages from PHPMailer
}
catch (Exception $e)
{
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
基本上,我需要一种方法来组合这两个脚本并将它们链接在一起,这就是我不确定如何做的事情。
答案 0 :(得分:4)
将邮寄代码放在一个函数中,例如send_mail()
,以便可以从不同的地方调用它。然后将数据库查询循环更改为:
while ($row = mysql_fetch_assoc($result)) {
send_mail($row['name'], $row['email'), "Text of the email");
}