0

我是 php 新手。我试图使用以下代码发送邮件。我的参考文件是这个。我认为这与我的结果部分有关。有人能帮忙吗?我的错误如下

Warning: Invalid argument supplied for foreach() in /home/mysite/public_html/sendmail.php on line 50

Warning: Invalid argument supplied for foreach() in /home/mysite/public_html/sendmail.php on line 70

我的完整代码如下请指导我

require_once 'lib/swift_required.php';
include('database.php');
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.mydomain.com', 25)
    ->setUsername('me@mydomain.com')
    ->setPassword('mypassword');

$transport = Swift_MailTransport::newInstance();
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);

// Send the message
//$result = $mailer->send($message);

//database connection part
$con = mysql_connect("localhost","username","password");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);

$sql = "SELECT email,name FROM email_test";     
$result = mysql_query($sql);

//tested the results, works fine 
while($row = mysql_fetch_array($result)) {
    echo "--".$row['email']."---";
}

//using result to get enail and user name
$replacements = array();
foreach ($result as $user) {
    $replacements[$user['email']] = array(
        '{email}'=>$user['email'],
        '{name}'=>$user['name']
    );
}

$decorator = new Swift_Plugins_DecoratorPlugin($replacements);
$mailer->registerPlugin($decorator);

$message = Swift_Message::newInstance()
    ->setSubject('Important notice for {name}')
    ->setBody("Hello {name}, we have reset your password");

foreach ($result as $user) {
    $message->addTo($user['email']);
}
4

1 回答 1

2
  1. 如评论:$result是一个mysql_resource,而不是一个数组。您需要fetch_row在该资源上运行才能真正获取详细信息。评论中提到(您可以将代码更新为现在的代码吗?)

  2. 当您第二次运行结果时,您需要“重置”结果集以从顶部开始。你可以通过mysql_data_seek($result, 0)说回到顶部来做到这一点。

于 2012-09-13T07:21:30.033 回答