PHPMailer html not showing images - php

I'm using PHPMailer to send the registration confirm email to my users with a full html file. The email shows perfectly except for the pictures are not loaded.
Here I attach my php code:
$mail = new PHPMailer(true);
$mail->CharSet = 'utf-8';
$mail->setFrom($this->Settings->SUPPORT_EMAIL_ADDRESS);
$mail->AddAddress($email);
$mail->Subject = dblang('registration_confirm_email_subject');
if (file_exists(APPPATH . '/views/email/registration/confirm.txt.' . $this->lang->lang() . '.php')) {
$mail->AltBody = $this->load->view('_email/registration/confirm.txt.' . $this->lang->lang() . '.php',
$emailData, true);
}
$mail->isHTML(true);
$mail->Body = $this->load->view('_email/registration/confirm.html.' . $this->lang->lang() . '.php',
$emailData, true);
if($mail->send()) {
swal_success('registration_email_send_title', 'registration_email_send_text');
redirect(site_url('home'));
}
Here I put a part of the html code. I've tried with relative and absolute urlfor the pictures path:
<img src="../../../../../../bets/assets/email/welovesports.png" alt="We Love Sports" border="0" width="290" height="92"
style="display: block;border: none;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;">

Since you've tried absolute urls with no luck.
looking on your code reference ../../../../../../bets/assets/email/
I suggest copy that image to very root of public_html -> /public_html/welovesports.png
and then reference it as <img src="http://your-domain.test/welovesports.png">
because the no. of directories your code suggests, can make it difficult to reference the correct path
OR Alternatively
you can use http://imgur.com/upload and host your image with them.
and on the gallery page of that image copy its direct link to use it
(it will be like http://i.imgur.com/RDz0KBs.png)
eg: http://i.imgur.com/RDz0KBs.png

Related

Image doesn't show when I send an email / swiftmailer [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am currently using Swiftmailer to send my emails. Everything works fine it is sending the emails however the emails are not showing the Logo I have put in. Here is the code:
require_once 'vendor/autoload.php';
require_once 'config/constants.php';
// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
->setUsername(EMAIL)
->setPassword(PASSWORD);
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
function sendVerificationEmail($userEmail, $token){
global $mailer;
$body = '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Verify Email</title>
</head>
<body>
<div class="not-verified-container">
<img src="logo.svg" class="mazaw-logo-not-verified">
<div class="container-without-logo">
<div class="not-verified-texts">
<h2>Account Verification</h2>
</div>
</div>
</div>
</body>
</html>';
// Create a message
$message = (new Swift_Message('Account Verification'))
->setFrom(EMAIL)
->setTo($userEmail)
->setBody($body, 'text/html');
// Send the message
$result = $mailer->send($message);
}
I would be very very thankful if someone could take a look and see what I have done wrong.
Thank you!
Embedding should work fine
<?php
$message = new Swift_Message('Your subject');
$message->setBody(
'<html>' .
' <body>' .
' <img src="' . $message->embed(Swift_Image::fromPath('image.png')) . '" />' .
' </body>' .
'</html>',
'text/html'
);
?>
You need to include the logo image in the email as an attachment. Not sure how thats done in Swiftmailer but when I googled it there are numerous examples including this one from here in StackOverflow.
Swiftmailer Attachments
$uploadedFileName = CUploadedFile::getInstance($model,'career_resume');
$uploadedFileName = $uploadedFile->tempName; // will be something like 'myfile.jpg'
$swiftAttachment = Swift_Attachment::fromPath($uploadedFileName);
$message->attach($swiftAttachment);
Also Google how to embed an image in Swiftmailer.

Moodle email templates

I am working on a Learning Management System build upon Moodle. I want to add an email header and footer for each email.
I did some change in Moodle for adding an image in ./lib/moodlelib.php as follows:
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
$usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
global $CFG, $PAGE, $SITE;
// Append image at top
if($messagehtml){
$tmp = $messagehtml;
// Added image here
$messagehtml = '<img src="'.$CFG->wwwroot.'/images/logo.png" alt="LMS" /><br/>';
// $messagehtml = $image;
$messagehtml .= $tmp;
}
if($messagetext){
$tmp = $messagetext;
// Added image here
$messagetext = '<img src="'.$CFG->wwwroot.'/images/logo.png" alt="LMS" /><br/>';
// $messagehtml = $image;
$messagetext .= $tmp;
}
....................
but I want the header and footer as fixed templates. Please help me.
You could create a message header in a language file (in English either directly under /lang/en or in a plugin) and then add the following string in the language file:
$string ['message_header'] = '<p> write here whatever your style and HTML structure you want in your header</p>
adding your image as well <img src="'.$CFG->wwwroot.'/images/logo.png" alt="LMS" />';
Then you could write a string for your footer as well:
$string ['message_footer'] = 'Your HTML footer here';
And finally you could insert your strings in the message:
$message = 'here your body';
// insert message header - if your language string is in /lang/moodle.php:
$message = get_string ( 'message_header') . $message;
// insert message footer - if your language string is in your /local/myplugin:
$message .= get_string ( 'message_footer', 'local_my_plugin' );
This way your header and footer may be customized at will if you change them directly in the language file (or, in the DB. See here).
a little bit too late, but i hope it helps others:
https://docs.moodle.org/dev/Themed_emails just look for e-mail templates in /var/www/html/moodle/lib/templates. The template with a name email_html.mustache should be the right one.

PHP mail() - Images don't always load

I have a PHP mail script which is basically the following:
$result = mail($to, $subject, $message, $headers);
if(!$result) {
echo "Error";
} else {
echo "Success";
}
The $message is a HTML email that mostly renders fine in my email client except the images seem to only load sporadically.
The images are all like so:
<img src='http://www.mywebsite.com/media/twitter.png' />
I don't understand why some would load and some wouldn't, when they are all set up the same way.
I've read that it's better to embed images into the email as attachments but I'm unsure how to do this. It seems that you add a line like so:
<img src='cid:123456789'>
But what does this reference? How would I encode an image like this?
Any help would be appreciated!! Thanks
You would have to base64 encode the file.
I found a code example on github. I have not tested it myself but should give you a good nudge in the right direction...
$picture = file_get_contents($file);
$size = getimagesize($file);
// base64 encode the binary data, then break it into chunks according to RFC 2045 semantics
$base64 = chunk_split(base64_encode($picture));
echo '<img src="data:' . $size['mime'] . ';base64,' . "\n" . $base64 . '" ' . $size[3] . ' />', "\n";
Source : https://gist.github.com/jasny/3938108
Just as a side note. Are the images that you are using web optimised? Large images might be blocked by email clients, or just not downloaded by email clients.

How can I send an base64 image on a mail body with PHP?

I'm trying to send an email with an image in base64 on the body with PHP using the code below, but the image never appears... If I change to an URL it works, but it doesn't with the base64... I tested the base64 on a new page only with <img src=base64> and worked too... What am I missing??
<?php
// recipients
$to = $_POST['email'];
// subject
$subject = 'Test';
// message
$message = '
<html>
<head>
<title>Test</title>
</head>
<body>
<img src="'.$_POST['imageFromOtherPage'].'"/>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
Here is my base64 image example: http://jsfiddle.net/28nP4/
I tried different things and the only way I found was uploading the image and getting the URL, I got that from this link: http://j-query.blogspot.in/2011/02/save-base64-encoded-canvas-image-to-png.html
It is very simple:
<?php
// requires php5
define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
And this generates an URL, so, instead of using <img src="'.$_POST['imageFromOtherPage'].'"/>, I use the generated URL. Worked perfectly!
i have the same problem, and finaly i resolved it. It might be helpful for you:
You can use SwiftMailer, but you must to add new Image TextHeader 'Content-Location'.
Here is the code:
$message = \Swift_Message::newInstance()->setSubject($subject)->setFrom($fromEmail, 'Name')->setTo($toEmail)->setBcc($bccEmails);
/*get uniqueID from cid:uniqueID */
$imageID = explode(':', $message->embed(\Swift_Image::fromPath('pathToTheImage')->setContentType('image/png')))[1];
/*Add Content-Location to image header*/
/** #var \Swift_Image $image */
$image = $message->getChildren()[0];
$image->getHeaders()->addTextHeader('Content-Location', $imageID);
$message->setBody('here you will have some html with <img src=$imageID alt="Embed Image">', 'text/html');
$mailer->send($message);
function for get all images url :
function getImagesFromMsg($msg, $tmpFolderPath)
{
$arrSrc = array();
if (!empty($msg))
{
preg_match_all('/<img[^>]+>/i', stripcslashes($msg), $imgTags);
//All img tags
for ($i=0; $i < count($imgTags[0]); $i++)
{
preg_match('/src="([^"]+)/i', $imgTags[0][$i], $withSrc);
//Remove src
$withoutSrc = str_ireplace('src="', '', $withSrc[0]);
//data:image/png;base64,
if (strpos($withoutSrc, ";base64,"))
{
//data:image/png;base64,.....
list($type, $data) = explode(";base64,", $withoutSrc);
//data:image/png
list($part, $ext) = explode("/", $type);
//Paste in temp file
$withoutSrc = $tmpFolderPath."/".uniqid("temp_").".".$ext;
#file_put_contents($withoutSrc, base64_decode($data));
}
//Set to array
$arrSrc[] = $withoutSrc;
}
}
return $arrSrc;
}
Try to test if $_POST['imageFromOtherPage'] contains the base64 , probably the code is too long for a Post, you would need to use php://input .
<img src="'.$_POST['imageFromOtherPage'].'"/>
Your POST needs to start with data:image/png;base64, to form a base64 encoded data: URI.
But even if you fix this, it is well possible that the E-Mail client you're viewing the message in doesn't support the method at all. data:URIs are a relatively new phenomenon - at least in the chronology of E-Mail clients, most of which are still in the process of discovering that there's a technology called CSS. The tried and tested method for images in E-Mails is to embed the image as an inline attachment.
Here are some approaches that don't rely on a library: Make PHP send an email with an inline image attachment
However, using a library like Swiftmailer may take away a lot of pain. Here is the appropriate Swiftmailer documentation.

Embedded image in HTML mail shows attached in stead of in template

I'm sending HTML mails with swiftmailer. It all works pretty great, my HTML mails are showing up just fine in all clients. I have quite the knowledge of building email templates. Sending them myself not so much...
The problem exists in gmail and hotmail. The image is not showing up. It shows just fine in Thunderbird for instance... gmail is leaving my image blank and adds it as an attachment (at the bottom of the mail, like i'm sending birthday pictures..).
Any ideas?
I've got the following code:
function deliverMail($subject, $data, $from, $to, $template){
if($_SERVER['SERVER_ADDR'] !== '::1'){
if (!is_array($to)){
$to = array($to);
}
$from = explode(",", $from);
//Create the Transport
$transport = Swift_SmtpTransport::newInstance('mail.xxx.nl', 25)
->setUsername('xxx')
->setPassword('xxx');
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance($subject);
$image = $message->embed(Swift_Image::fromPath($_SERVER['DOCUMENT_ROOT'].'/templates/emails/xxx.jpg'));
// open the file
$sourcefile = $_SERVER['DOCUMENT_ROOT'].'/templates/emails/'.$template.'.html.tpl';
$fh = fopen($sourcefile, 'r');
$htmltemplate = fread($fh, filesize($sourcefile));
fclose($fh);
// set the content
if($template == 'confirm'){$replaceOld = array("[*code*]", "[*imgsrc*]");}
if($template == 'notify'){$replaceOld = array("[*url*]", "[*imgsrc*]");}
$replaceNew = array($data, $image);
$body = str_replace($replaceOld, $replaceNew, $htmltemplate);
$message->setFrom(array($from[0] => $from[1]))
->setTo($to)
->setBody($body, 'text/html');
if (!$mailer->send($message, $failures)){
return "Failures:";
return print_r($failures);
}else{
return 'success';
}
}
}
Which will render the image in my template here:
<td id="head" height="80" width="640" colspan="3" valign="top" align="left">
<image src="[*imgsrc*]" width="140" height="80" alt="xxx"/>
</td>
I have seen this behaviour in GMail as well and think this is just how GMail displays mail with embedded images.
See this link for more information:http://www.getelastic.com/email-design-for-gmail/
Did you know that Gmail disables
images in HTML emails by default, even
if your customer has added you to his
or her safe list?
Wow, finally settled this. "image" is not a valid HTML tag of course... after trying 3 different php libraries i found this..
<td id="head" height="80" width="640" colspan="3" valign="top" align="left">
<image src="[*imgsrc*]" width="140" height="80" alt="xxx"/>
</td>

Categories