Search code examples
yii2swiftmailer

Unable to embed image with Swiftmailer with Yii2


I am trying to embed an image in my Email using swiftmailer but it is not getting embed in it. I have tried every solution provided in the forums but still not able to make it work. Below is my code. Please note that I am able to HTML contents in my template but just image is not getting embedded in it.

$message = Yii::$app->mailer->compose('registration', ['imgN'=>'\Yii::getAlias('@webroot/assets/image.png')]);

return $message->setFrom($from)->setTo($to)->setSubject(self::$subject)->send();

I have also tried using :

i) 'imgN'=> Yii::getAlias('@web/assets/image.png'),
ii) 'imgN'=>Yii::getAlias('@app/assets/image.png'),
iii)'imgN'=> '@app/web/assets/image.png',

Code in the View:

 <?php
     use yii\swiftmailer\Message;
     $message = new Message;
    ?>

and in HTML body:

    <img src="<?= $message->embed($imgN); ?>" alt="No Image"/>

Please point any mistake I may have done? It would be a big help. Thanks!


Solution

  • Try

    $message = Yii::$app->mailer->compose();
    $message->setFrom($from);
    $message->setTo($to);
    $message->setSubject(self::$subject);
    $message->setHtmlBody(Yii::$app->mailer->render('registration', [
        'img' => $message->embed(\Yii::getAlias('@app/assets/image.png')),
    ], Yii::$app->mailer->htmlLayout));
    
    return $message->send();
    

    And in view:

    <img src="<?= $img ?>">