phpmailer从文本文件中获取收件人

时间:2018-03-09 12:19:29

标签: php file phpmailer

在发布此帖子之前,我搜索了我的问题,但我只看到如何从数据库或其他人那里获取收件人只有mail()函数。

我想从txt文件发送电子邮件,但我的代码只发送来自文本文档的第一封电子邮件。

  <?php
  include("msd/mail.php");
  $file = fopen("emails.txt",  "r");
       $line = fgets($file);
        $to = $line;
  $subject = "Approve your signup";
  $body = "Hello, to approve your registration please click this link";
  $mail = new Mail();
  $mail->CharSet = 'UTF-8';
  $mail->FromName = "myweb.com";
  $mail->addAddress($to);
  $mail->subject($subject);
  $mail->body($body);
  if(!$mail->send())
 {
            echo "Error Sending Email!"; 
         }
         else
        { 
            echo "Mail sent!"; 
        }

    ?>

emails.txt

test@gmail.com
test2@gmail.com
test3@gmail.com

2 个答案:

答案 0 :(得分:0)

您需要逐行读取文本文件,然后将其放入数组并运行循环以添加地址

<?php
    include("msd/mail.php");
    $file = fopen("test.txt","r");
    $emailArray = array();
    while(! feof($file))
    {
        $emailArray[] = fgets($file). "<br />";
    }
    $subject = "Approve your signup";
    $body = "Hello, to approve your registration please click this link";
    $mail = new Mail();
    $mail->CharSet = 'UTF-8';
    $mail->FromName = "myweb.com";
    foreach($emailArray as $val)
    {
        $mail->addAddress($val);
    }
    $mail->subject($subject);
    $mail->body($body);
    if(!$mail->send())
    {
        echo "Error Sending Email!"; 
    }
    else
    { 
        echo "Mail sent!"; 
    }

?>

答案 1 :(得分:0)

您可以随时循环执行此操作。请尝试以下代码:

<?php
  include("msd/mail.php");
  $file = fopen("emails.txt",  "r");
  if($file){
    $array = explode("\n", fread($fp, filesize($file)));
  }
  $subject = "Approve your signup";
  $body = "Hello, to approve your registration please click this link";
  $mail = new Mail();
  $mail->CharSet = 'UTF-8';
  $mail->FromName = "myweb.com";
  for($i=0;$i<=count($array)-1;$i++){
        $mail->AddAddress($array[$i]);
  } 
  $mail->subject($subject);
  $mail->body($body);
  if(!$mail->send())
    {
        echo "Error Sending Email!"; 
    }
    else
    { 
        echo "Mail sent!"; 
    }

注意请确保该文件由php

读取