AcMailer\Service\MailService::setBody PHP Method

setBody() public method

Sets the message body
See also: AcMailer\Service\MailServiceInterface::setBody()
public setBody ( Zend\Mime\Part | Zend\Mime\Message | string $body, string $charset = null )
$body Zend\Mime\Part | Zend\Mime\Message | string Email body
$charset string
    public function setBody($body, $charset = null)
    {
        if (is_string($body)) {
            // Create a Mime\Part and wrap it into a Mime\Message
            $mimePart = new Mime\Part($body);
            $mimePart->type = $body != strip_tags($body) ? Mime\Mime::TYPE_HTML : Mime\Mime::TYPE_TEXT;
            $mimePart->charset = $charset ?: self::DEFAULT_CHARSET;
            $body = new Mime\Message();
            $body->setParts([$mimePart]);
        } elseif ($body instanceof Mime\Part) {
            // Overwrite the charset if the Part object if provided
            if (isset($charset)) {
                $body->charset = $charset;
            }
            // The body is a Mime\Part. Wrap it into a Mime\Message
            $mimeMessage = new Mime\Message();
            $mimeMessage->setParts([$body]);
            $body = $mimeMessage;
        }
        // If the body is not a string or a Mime\Message at this point, it is not a valid argument
        if (!is_string($body) && !$body instanceof Mime\Message) {
            throw new InvalidArgumentException(sprintf('Provided body is not valid. It should be one of "%s". %s provided', implode('", "', ['string', 'Zend\\Mime\\Part', 'Zend\\Mime\\Message']), is_object($body) ? get_class($body) : gettype($body)));
        }
        // The headers Content-type and Content-transfer-encoding are duplicated every time the body is set.
        // Removing them before setting the body prevents this error
        $this->message->getHeaders()->removeHeader('contenttype');
        $this->message->getHeaders()->removeHeader('contenttransferencoding');
        $this->message->setBody($body);
        return $this;
    }

Usage Example

 public function testAttachmentsAreAddedAsMimeParts()
 {
     $cwd = getcwd();
     chdir(dirname(__DIR__));
     $this->mailService->setAttachments(array('attachments/file1', 'attachments/file2', 'attachments/dir/file3', 'invalid/attachment'));
     $this->mailService->setBody('Body as string');
     $result = $this->mailService->send();
     $this->assertTrue($result->isValid());
     /* @var Mime\Message $body */
     $body = $this->mailService->getMessage()->getBody();
     $this->assertInstanceOf('Zend\\Mime\\Message', $body);
     // The body and the three attached files make it a total of 4 parts
     $this->assertCount(4, $body->getParts());
     chdir($cwd);
 }
All Usage Examples Of AcMailer\Service\MailService::setBody