Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send image in body of email in YII?

Tags:

php

yii2

Here is code of send mail function I want to send image in set body.

public function SendMail($id) {
    $message = new YiiMailer('', array());
    $message->setFrom('[email protected]', 'test');
    $message->setTo('[email protected]');
    $message->setSubject('Test');
    $message->IsHTML(true);

    $message->setBody(??????);

    if ($message->send()) {

  }
 }

Give me code for send image in set body in yii.

I dont know how to send image in set body?

like image 387
Kevin Patel Avatar asked Oct 26 '15 05:10

Kevin Patel


2 Answers

What about these

$message[] = Yii::$app->mailer->compose('downNotify', [
    'image' => Url::to('@app/web/mail/images/logo.png')
])

$message->setBody($message);

Or Refer Here

Yii::$app->mailer->compose('embed-email', ['imageFileName' => '/path/to/image.jpg'])
// ...
->send();

<img src="<?= $message->embed($imageFileName); ?>">

Or Refer Here

$uploadedFile = CUploadedFile::getInstance($model,'anexo'); $msg->attach($uploadedFile);

Or This too

$image = Swift_Image::fromPath(dirname(Yii::app()->getBasePath()) . '/images/someimage.jpg');
$cid = $message->embed($image);    
$message->setBody(array('cid' => $cid), 'text/html');

So in protected /views/mail/test.php:

<b>An embedded inline image:</b><br><br>
<img src="<?php echo $cid; ?>" alt="WTF went wrong?" />

Or this toooo(Adding as attachment)

Yii::setPathOfAlias('webroot.images.mail', '/path/to/your/images/mail/dir');
like image 173
Abdulla Nilam Avatar answered Nov 11 '22 23:11

Abdulla Nilam


I recently found a way to do this. My solution required an update of phpMailer to 5.2.x because previous versions use set_magic_quotes_runtime() which is depracated in PHP 5.4 and later. If you use 5.3 you should not need to update phpMailer.

phpMailer has a way to embed images by putting a placeholder in the body then assigning images to the placeholders.

In your body (has to be html) you add the placeholder like this:

<img src="cid:header"/>

Then where you are sending the mail you assign the image to the placeholder like this:

Yii::app()->mailer->IsHTML(true);
$path = Yii::getPathOfAlias('application.views.email');
Yii::app()->mailer->AddEmbeddedImage($path . DIRECTORY_SEPARATOR. "emailHeader.png", "header", "alertHeader.png");

In my case the images are in the same view folder as the email template. AddEmbeddedImage takes 3 parameters:

  • path to the image
  • cid identifier
  • image name as will appear in the email
like image 26
Mark A. Tagliaferro Avatar answered Nov 11 '22 22:11

Mark A. Tagliaferro