Php - imap_delete - 删除刚刚选择的电子邮件

时间:2015-05-31 23:20:37

标签: php html email imap

我有一个脚本打印出从imap服务器获取的所有收件箱电子邮件。 我添加了一个删除提交按钮,按下时需要只删除属于该按钮的电子邮件。但是,现在脚本会在按下任何删除按钮时删除所有电子邮件。下面简化的代码:

<?php    
foreach($emails as $email_number) {
?>
 <form method="post">
        <th class="tg-031e"><input type="submit" name="delete_inbox" value="Delete"></th>
        </form>

<?php
if(isset($_POST['delete_inbox'])){
$check = imap_mailboxmsginfo($imap);
echo "Messages before delete: " . $email_number . "<br />\n";
imap_delete($imap, $email_number);
$check = imap_mailboxmsginfo($imap);
echo "Messages after  delete: " . $check->Nmsgs . "<br />\n";
imap_expunge($imap);
$check = imap_mailboxmsginfo($imap);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";
}
}?>

有关如何通过按删除按钮删除所选电子邮件的任何想法?另外,为什么我必须刷新页面两次才能看到删除后的更改?

1 个答案:

答案 0 :(得分:0)

电子邮件的删除表单和电子邮件本身之间似乎没有任何关联。 PHP无法知道您要删除的确切电子邮件。

如前所述,一个想法是将电子邮件的i.d放在每封电子邮件旁边的提交按钮的值中。

然后,您可以从delete_inbox输入的发布数据中获取该内容。

 <?php
    if(isset($_POST['delete_inbox'])){
    // Retrieve email i.d value from delete_inbox button
    $email_to_delete = $_POST['delete_inbox'];
    $check = imap_mailboxmsginfo($imap);


echo "Messages before delete: " . $email_number . "<br />\n";
// Delete selected email
imap_delete($imap, $email_to_delete);
$check = imap_mailboxmsginfo($imap);
echo "Messages after  delete: " . $check->Nmsgs . "<br />\n";
imap_expunge($imap);
$check = imap_mailboxmsginfo($imap);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";
}

foreach($emails as $email_number) {
?>
 <form method="post">
        <th class="tg-031e"><button type="submit" name="delete_inbox" value="<?php echo $email_number; ?>">Delete</button></th>
        </form>

<?php }?>

注意:我还从foreach循环中删除了代码的$ _POST部分。我没有看到任何理由在那里。