vikesh
vikesh

Reputation: 61

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!

Upvotes: 2

Views: 2999

Answers (2)

ChrisB
ChrisB

Reputation: 631

I wanted to display embedded images with the html of an email. I found that you couldn't do the normal Yii::$app->mailer->compose( 'view_file' ) because you need to reference the "cid" of the embedded image within your html.

You therefore need to create the email object first

  $email = Yii::$app->mailer->compose($view, ['model' => $model ])
                    ->setFrom($from)
                    ->setTo($emailTo)
                    ->setSubject($subject);

Then create each embedded object

  $cid = $email->embed($model->filename,[
                    'fileName' => $model->id,".jpg",
                    'contentType' => 'image/jpeg'
                     ]);
  // save the returned cid
  $images[$item->id] = '<img src="'.$cid.'"/>';

Then create the html by rendering your view (or however else you do it)

  $html = Yii::$app->mailer->render('@common/mail/receipt', ['model' => $this, 'images' => $images ]);
  $email->setHtmlBody($html);

then in your view echo out the images

  foreach ( $images as $image )
      echo $image;

then send the email

   $result = $email->send()

Upvotes: 0

Bizley
Bizley

Reputation: 18021

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 ?>">

Upvotes: 2

Related Questions