Multiple attachment with laminas-mail


I’m trying to send multiple attachment using this below code, but it’s not working. It’s sending only one file. Can you please let me know how to send multiple attachment with laminas-mail.

And second problem is, mail body is coming as blank .

    use Laminas\Mail\Message;
    use Laminas\Mime\Message as MimeMessage;
    use Laminas\Mime\Mime;
    use Laminas\Mime\Part as MimePart;
    use Laminas\Mail\Transport\Sendmail;

    $textContent = 'Testing';
    $htmlMarkup = '<h1>HTML Content</h1>';
    $attachments = array('1.txt','2.txt','3.jpg','4.pdf');

    $message = new Message();
    $message->setSubject('Sending an email from Laminas\Mail!');

    $body = new MimeMessage();

    $text           = new MimePart($textContent);
    $text->type     = Mime::TYPE_TEXT;
    $text->charset  = 'utf-8';
    $text->encoding = Mime::ENCODING_QUOTEDPRINTABLE;

    $html           = new MimePart($htmlMarkup);
    $html->type     = Mime::TYPE_HTML;
    $html->charset  = 'utf-8';
    $html->encoding = Mime::ENCODING_QUOTEDPRINTABLE;

    $content = new MimeMessage();
    // This order is important for email clients to properly display the correct version of the content
    $content->setParts([$text, $html]);

    $contentPart = new MimePart($content->generateMessage());

    foreach($attachments as $attachment) {
    	$file              = new MimePart(fopen($attachment, 'r'));
    	$file->type        = Mime::TYPE_OCTETSTREAM;
    	$file->filename    = $attachment;
    	$file->disposition = Mime::DISPOSITION_ATTACHMENT;
    	$file->encoding    = Mime::ENCODING_BASE64;
    	$body = new MimeMessage();
    	$body->setParts([$contentPart, $file]);

    //$message = new Message();

    $contentTypeHeader = $message->getHeaders()->get('Content-Type');

    $transport = new Sendmail();

The problem is this line your loop:

It will set the parts always completely new. Use the method Laminas\Mime\Message::addPart().