Email in loop sends the same file using Email clas

2019-06-02 04:41发布

问题:

Hey I'm using Codeigniter's Email helpers, and expiriencing a wierd issue. I have the following code :

        $path = mpdf_create_billing($html);
        $this->load->library('email');
        $this->email->set_newline("\r\n");
        $this->email->from('no-reply@foo.com');
        $this->email->to("foo@gmail.com");
        $this->email->subject('Invoice for  '.date('d/m/y'));
        $this->email->message($message);
        $this->email->attach($path);
        if($this->email->send())
            echo "Email Sent Successfully to $email with the file $path<br>";
        else
            echo "Should be sending email to $email , but i didn't<br>";

Now this code is inside a foreach loop,twice in this case. mpdf_create_billing returns path to a PDF file. now this code echos 2 different file paths, but the email is the same and in both loop runs and both of the emails contain the same file, though the file paths are different.

Anyone knows how to resolve it? this is what outputs for me :

Email Sent Successfully to foo@foo.com with the file
   /path/to/pdf/Invoice_1368452801.82065190eec1c85eb.pdf

Email Sent Successfully to foo@foo.com with the file 
  /path/to/pdf/Invoice_1368452804.53475190eec482917.pdf

Could this be a problem with my SMTP server that send the emails? I tried it on 2 mail accounts, and same result.

回答1:

Perhaps you should clear $this->email?

From the CodeIgniter docs:

$this->email->clear()

Initializes all the email variables to an empty state. This function is intended for use if you run the email sending function in a loop, permitting the data to be reset between cycles.

foreach ($list as $name => $address)
{
    $this->email->clear();

    $this->email->to($address);
    $this->email->from('your@example.com');
    $this->email->subject('Here is your info '.$name);
    $this->email->message('Hi '.$name.' Here is the info you requested.');
    $this->email->send();
}

If you set the parameter to TRUE any attachments will be cleared as well:

$this->email->clear(TRUE);

Looks to me this is what you are doing?

Link CI3: https://www.codeigniter.com/user_guide/libraries/email.html

Link CI2: https://www.codeigniter.com/userguide2/libraries/email.html