Codeigniter: Email attachment of last emails not cleared while sending multiple emails in loop

11,926

Solution 1

You need to use $this->email->clear(); to clean out the variables set within the loop. Read the manual.

Solution 2

You need to reset it in CodeIgniter.

At the end of the loop add:

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

This resets all email variables including the attachments, allowing you to create a new mail.

Share:
11,926
anils
Author by

anils

I am a software Engineer. I works in Python, JavaScript, jQuery, CSS, Pyside and PHP.

Updated on June 05, 2022

Comments

  • anils
    anils almost 2 years

    My code sends multiple emails in loop with attachment,

    Problem is attachments of last(previous all) emails get attached to next email.

    ex. suppose 3 emails in database with 1 attachment in each(a1.pdf, a2.pdf, a3.pdf) then, it sends email with attachment as

    email 1:

    attachment :a1.pdf

    email 2:

    attachment :a1.pdf, a2.pdf

    email 3:

    attachment :a1.pdf, a2.pdf, a3.pdf

    I am using codeigniter framework.

    My code is (this code is called in loop)

    . . .

    $this->email->subject($item->subject);

            $this->email->message($message);
            $attachments='';
            if(strlen($item->attachment) > 5)
            {
                $attachments = explode(',', $item->attachment);
                foreach($attachments as $attachment)
                {
                    if(strlen($attachment)>5)
                    $this->email->attach(FCPATH . 'attachments/' . $attachment);                    
                }                
    
            }
    
          $this->email->send();
    

    . . .

  • Kentot
    Kentot over 8 years
    This works but in my case, it does not attached file on the last loop.
  • Tobe_Sta
    Tobe_Sta about 5 years
    Remember to include TRUE when calling clear() in order to remove any current attachments.
  • Tobe_Sta
    Tobe_Sta about 5 years
    Upvoted as correct answer as clear() requires a TRUE boolean to clear the attachments.