Mail Mime image in email body not showing up using MailMime addHtml(...) - php

Mail_Mime 1.8.9
Mail 1.2.0
php 5.4.12
project = run from my localhost dev computer (LAN).
Hello, I am attempting to add an image to my email I am sending out using MailMime. The image never loads. I'll go through the steps below:
Here I am stripping everything off of the image but the image name and extension (ie:noimage.jpg). I then create a link for non image related purposes, I then create the image tag using the stripped image name and extension.
$url = substr($baseImage, 36);
$domainName = DomainNameUtil::getWebSiteDomainName();
$projectPath = DomainNameUtil::getPathToProject();
$productUrl = $domainName . $projectPath . "/client/app/#/products/" . $product->id;
$productLink = "<a href='$productUrl'>$product->name</a>";
$string = "<img src='$url' /><br />";
Here I am sending the message
$mailConfig = MailConfigurationUtil::getMailConfigurationData();
$headers = array (
'From' => $from,
'To' => $to,
'Subject' => $subject
);
$crlf = "\n";
$mime = new Mail_mime(array('eol' => $crlf));
$mime->setHTMLBody($body);
$headers = $mime->headers($headers);
$smtp = Mail::factory('smtp', array (
'host' => $mailConfig->mailServer,
'port' => $mailConfig->port,
'auth' => true,
'username' => $mailConfig->userName,
'password' => $mailConfig->password
));
$productManager = new ProductManager();
$ordersManager = new OrdersManager();
$orderVirtualItem = $ordersManager->getOrderVirtualItemByBoxId($boxId);
$product = $productManager->getProductById($orderVirtualItem->itemId);
$url = $product->baseImage;
$domain = DomainNameUtil::getWebSiteDomainName();
$path = DomainNameUtil::getPathToProject();
$r = substr($url, 5);
$finalUrl = $domain . $path . $r;
$mime->addHTMLImage(file_get_contents($finalUrl),'image/jpeg',basename("noimage"),false, "blackstone");
$body = $mime->get();
$mail = $smtp->send($to, $headers, $body);
In the example above, I know the image is called noimage.jpeg, so in the addHtmlImage above I simply stated the name. I am under the impression that the name used in addHtmlImage has to be the same name as the image name in the image src tag in the html body.
When I actually send my email I get the email and I get some text saying there is an image, but the image tag in my email body does not load.
Also, looking at it under firebug it has a proxy attached to the image src. Also it references it as PROXYADDRESS#http://noimage.jpg
Anyone have experience in this that can help me understand why the image is not loading?
For reference, I saw someone posting this method online and tried copying them. before this I had even tried putting the whole url in the image src and not adding the image to MIME, and it did not work.

i got pretty similar problem here.
What i got so far: it depends on phpversion (and installed Mail_Mime).
Mail_Mime seems to be "broken" under php 5.4.30
If i run my script under php 5.2.17 all images show up correctly
If i run my script under php 5.4.30 all images do not show up correctly
when i compare both sourcecodes, it seems, Mail_Mime under 5.4.30 gets messy with the order of boundarys and the Content-Type:
Content-Type: multipart/alternative; in 5.2.17
Content-Type: multipart/related; in 5.4.30enter image description here

When specifying a context-id (the last parameter to addHtmlImage()) you must reference the image in the html message correctly: <img src="cid:context-id#local" />. Of course replacing context id with your own context id for each image to show.

Related

Sending mail large attachment - ZF2

i just ran into a problem, when sending mails with attachments larger than about 2.5Mb from a server. Sending emails with smaller attachments work, but as soon the critical size of about 2 or 2.5Mb is reached, the mail is not send anymore.
The PDF files and merged target PDF are created without problem, no matter of the size. But only smaller PDF files are send by mail. Not even an empty mail is send, when the attachments are too large.
The process is a follows:
1) The php script creates several PDF files.
2) Those files are merged through gs
$finCmd = 'gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile='.$pathDest.$pdfFilename.' input1.pdf input2.pdf input3.pdf';
// Create PDF
$execResult = exec($finCmd);
3) The email body is created
protected function setBodyHtmlpart($content, $pdfFilepath = null, $pdfFilename = null) {
$content="<p><span style='font-size:10.0pt;font-family:\"Arial\",\"sans-serif\";color:black;'>".$content.'</span></p>';
$html = new MimePart($content.$this->getSignature());
$html->type = "text/html";
$body = new MimeMessage();
if ($pdfFilename != '') {
$pdfAttach = new MimePart(file_get_contents($pdfFilepath.$pdfFilename));
$pdfAttach->type = 'application/pdf';
$pdfAttach->filename = $pdfFilename;
$pdfAttach->encoding = \Zend\Mime\Mime::ENCODING_BASE64;
$pdfAttach->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
$body->setParts(array($html, $pdfAttach));
} else {
$body->setParts(array($html));
}
return $body;
}
4) The email is send with:
protected function send($fromAddress, $fromName, $toAddress, $toName, $subject, $bodyParts)
{
// setup SMTP options
$options = new SmtpOptions(array(
'name' => 'XServer',
'host' => 'xServer',
'port' => 25,
'connection_class' => 'plain',
'connection_config' => array(
'username' => 'Xusername',
'password' => 'Xpassword',
),
));
$mail = new Message();
$mail->setBody($bodyParts);
$mail->setFrom($fromAddress, $fromName);
$mail->setTo($toAddress, $toName);
$mail->setSubject($subject);
$transport = new SmtpTransport($options);
$transport->send($mail);
}
Any hints are welcome, as i am totaly lost.
I thought there could be race problem: exec is not finished, but script already tries to send the mail and cancels. But i than would at least receive an empty email.
Edit:
Changing then Mime\Mime::ENCODING_BASE64 delivers the mails, but PDF files are corrupted.
Have you tried using type Octetstream
$pdfAttach->type = Mime::TYPE_OCTETSTREAM;
$pdfAttach->encoding = Mime::ENCODING_BASE64;
It seems like, that the issue is the mime encoding.
All options:
Zend_Mime::ENCODING_7BIT: '7bit' --> corrupted file
Zend_Mime::ENCODING_8BIT: '8bit'; --> corrupted file
Zend_Mime::ENCODING_QUOTEDPRINTABLE: 'quoted-printable' --> corrupted
file
Zend_Mime::ENCODING_BASE64: 'base64' --> file not send
did not work.
Developed a solution with PHPMailer.
Worked out.

PDF Attachment missing with PHPMailer

I have a problem with PHPMailer. It seems that i have customers that do no receive the attachment in their outlook box. Below is the code i am using. I tested it at my private gmail where the attachment is visible.
Could it be because i am using a stringAttachment instead of a real file?
$mail = new SMail();
$mail->SetFrom('administratie#domain.nl', 'Domain b.v.');
$mail->AddAddress($invoice->SAddress()->email);
$mail->Subject = 'Factuur ' . $invoice->getReferenceNumber();
$mail->AddStringAttachment($this->getAction($invoice->invoiceId, null, 'S'), $invoice->getReferenceNumber() . '.pdf', 'base64', 'application/pdf');
$this->objTemplate->assign(array(
'title' => 'Uw factuur',
'referenceNumber' => $invoice->getReferenceNumber(),
));
$mail->MsgHTML($this->objTemplate->render('mail/invoice.tpl', false, true));
The problem was the fact that outlook blocked the inline image content on which also the attachment broke somehow.

php Mail_MIME - Generating and Attaching PDF

I am trying to write a PHP script that will generate a PDF and email it. My PDF generator works perfectly as an independent URL, but for some reason when I try to make the script email the generated PFD, the received file can't be opened. Here is the code:
include_once('Mail.php');
include_once('Mail/mime.php');
$attachment = "cache/form.pdf";
// vvv This line seems to be where the breakdowns is vvv
file_put_contents( $attachment, file_get_contents( "http://www.mydomain.com/generator.php?arg1=$arg1&arg2=$arg2" ) );
$message = new Mail_mime();
$message->setTXTBody( $msg );
$message->setHTMLBody( "<html><body>$msg</body></html>" );
$message->addAttachment( $attachment );
$body = $message->get();
$extraheaders = array( "From" => $from,
"Cc" => $cc,
"Subject" => $sbj );
$mail = Mail::factory("mail");
$headers = $message->headers( $extraheaders );
$to = array( "Jon Doe <jon#mydomain.com>",
"Jane Doe <jane#mydomain.com>" );
$addresses = implode( ",", $to );
if( $mail->send($addresses, $headers, $body) )
echo "<p class=\"success\">Successfully Sent</p>";
else
echo "<p class=\"error\">Message Failed</p>";
unlink( $attachment );
The line that I marked does generate a PDF file in the cache folder, but it will not open, so that seems to be a problem. However, when I try to attach a PDF file already exists, I have the same problem. I have tried $message->addAttachment( $attachment, "Application/pdf" ); as well, and it does not seem to make a difference.
Typically web server directories should have write permissions locked down. This is probably why you are experiencing problems with file_put_contents('cache/form.pdf').
// A working example: you should be able to cut and paste,
// assuming you are on linux.
$attachment = "/var/tmp/Magick++_tutorial.pdf";
file_put_contents($attachment, file_get_contents(
"http://www.imagemagick.org/Magick++/tutorial/Magick++_tutorial.pdf"));
Try changing where you are saving the pdf to a directory that allows write and read permissions to everyone. Also make sure this directory is not on your web server.
Also try changing the following three things
From
$message = new Mail_mime();
To
// you probably don't need this the default is
// $params['eol'] - Type of line end. Default is ""\r\n""
$message = new Mail_mime("\r\n");
From
$extraheaders = array(
"From" => $from,
"Cc" => $cc,
"Subject" => $sbj,
);
To
$extraheaders = array(
"From" => $from,
"Cc" => $cc,
"Subject" => $sbj,
'Content-Type' => 'text/html'
);
From
$message->addAttachment($attachment);
To
// the default second argument is $c_type = 'application/octet-stream'
$isAttached = $message->addAttachment($attachment, 'aplication/pdf');
if ($isAttached !== true) {
// an error occured
echo $isAttached->getMessage();
}
And you always want to make sure that you call
$message->get();
before
$message->headers($extraheaders);
or the whole thing wont work
I am pretty sure it must be an ini problem blocking file_get_contents(). However I came up with a better solution. I reworked the generator.php file and turned it in to a function definition. So I've got:
include_once('generator.php');
$attachment = "cache/form.pdf";
file_put_contents( $attachment, my_pdf_generator( $arg1, $arg2 ) );
...
$message->addAttachment( $attachment, "application/pdf" );
This way I do not need to write the file first. It works great (although I am still having slight issues with Outlook/Exchange Server, but I think that is a largely unrelated issue).

problem sending email with attachment

I'm new to using EWS from Exchangeclient classes.
I'm looking for a simple example how to send an email with an attachment. I've found examples about how to send an email but not sending an email with an attachment.
This is my script:
$exchangeclient = new Exchangeclient();
$exchangeclient->init($username, $password, NULL, 'ews/Services.wsdl');
$exchangeclient->send_message($mail_from, $subject, $body, 'HTML', true, true);
I have the following soap request.
$CreateItem->MessageDisposition = "SendAndSaveCopy";
$CreateItem->SavedItemFolderId->DistinguishedFolderId->Id = "sentitems";
$CreateItem->Items->Message->ItemClass = "IPM.Note";
$CreateItem->Items->Message->Subject = $subject;
$CreateItem->Items->Message->Body->BodyType = $bodytype;
$CreateItem->Items->Message->Body->_ = $content;
$CreateItem->Items->Message->ToRecipients->Mailbox->EmailAddress = $to;
$CreateItem->Items->Message->Attachments->FileAttachment->AttachmentId = $attach['AttachmentId'];
$CreateItem->Items->Message->Attachments->FileAttachment->Name = $attach['Name'];
$CreateItem->Items->Message->Attachments->FileAttachment->ContentType = $attach['ContentType'];
$CreateItem->Items->Message->Attachments->FileAttachment->ContentId = $attach['AttachmentId'];
$CreateItem->Items->Message->Attachments->FileAttachment->Content = $attach['ContentId'];
$CreateItem->Items->Message->Attachments->FileAttachment->Size = $attach['Size'];
The error I am getting is:
Fatal error: Uncaught SoapFault exception: [a:ErrorSchemaValidation] The request failed schema validation: The required attribute 'Id' is missing.
In order to send email with an attachment you have to first create the Message (Item) without any recipients (and a MessageDisposition of "SendToNone" or something like that) and save it in your Drafts folder. THEN create a request for a CreateAttachment, like so, where $key is the changekey of the item you created earlier (you have to read back the server response and save the changekey somewhere, because the changekey changes for an item with every modification it undergoes):
$attachrequest->ParentItemId->ChangeKey = $key;
$attachrequest->Attachments->FileAttachment->Name = $attachment_name;
$attachrequest->Attachments->FileAttachment->ContentLocation = $attachment;
$attachrequest->Attachments->FileAttachment->Content = $attachment_content;
$attachrequest->Attachments->FileAttachment->ContentType = $attachment_contenttype;
$response = self::$ews->CreateAttachment($attachrequest);
THEN you update the message (with an UpdateItem) to include recipients and so that the MessageDisposition is something like SendToAllAndSaveCopy.
(Disclaimer: I'm using this method now and it's all working fine, except for identifying the right format for Attachments->FileAttachment->Content, which looks like it should be the encoded base64 data of the attachment--but my computer can't open the attachments I'm sending.)
At any rate I believe this is the way to do it, and certainly I have been able to send messages with attachments with it.

Send Mail from raw body for testing purposes

I am developing a PHP application that needs to retrieve arbitrary emails from an email server. Then, the message is completely parsed and stored in a database.
Of course, I have to do a lot of tests as this task is not really trivial with all that different mail formats under the sun. Therefore I started to "collect" emails from certain clients and with different contents.
I would like to have a script so that I can send out those emails automatically to my application to test the mail handling.
Therefore, I need a way to send the raw emails - so that the structure is exactly the same as they would come from the respective client. I have the emails stored as .eml files.
Does somebody know how to send emails by supplying the raw body?
Edit:
To be more specific: I am searching for a way to send out multipart emails by using their source code. For example I would like to be able to use something like that (an email with plain and HTML part, HTML part has one inline attachment).
--Apple-Mail-159-396126150
Content-Transfer-Encoding: quoted-printable
Content-Type: text/plain;
The plain text email!
--=20
=20
=20
--Apple-Mail-159-396126150
Content-Type: multipart/related;
type="text/html";
boundary=Apple-Mail-160-396126150
--Apple-Mail-160-396126150
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html;
charset=iso-8859-1
<html><head>
<title>Daisies</title>=20
</head><body style=3D"background-attachment: initial; background-origin: =
initial; background-image: =
url(cid:4BFF075A-09D1-4118-9AE5-2DA8295BDF33/bg_pattern.jpg); =
background-position: 50% 0px; ">
[ - snip - the html email content ]
</body></html>=
--Apple-Mail-160-396126150
Content-Transfer-Encoding: base64
Content-Disposition: inline;
filename=bg_pattern.jpg
Content-Type: image/jpg;
x-apple-mail-type=stationery;
name="bg_pattern.jpg"
Content-Id: <4BFF075A-09D1-4118-9AE5-2DA8295BDF33/tbg.jpg>
/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAASAAA/+IFOElDQ19QUk9GSUxFAAEB
[ - snip - the image content ]
nU4IGsoTr47IczxmCMvPypi6XZOWKYz/AB42mcaD/9k=
--Apple-Mail-159-396126150--
Using PHPMailer, you can set the body of a message directly:
$mail->Body = 'the contents of one of your .eml files here'
If your mails contain any mime attachments, this will most likely not work properly, as some of the MIME stuff has to go into the mail's headers. You'd have to massage the .eml to extract those particular headers and add them to the PHPMailer mail as a customheader
You could just use the telnet program to send those emails:
$ telnet <host> <port> // execute telnet
HELO my.domain.com // enter HELO command
MAIL FROM: sender#address.com // enter MAIL FROM command
RCPT TO: recipient#address.com // enter RCPT TO command
<past here, without adding a newline> // enter the raw content of the message
[ctrl]+d // hit [ctrl] and d simultaneously to end the message
If you really want to do this in PHP, you can use fsockopen() or stream_socket_client() family. Basically you do the same thing: talking to the mailserver directly.
// open connection
$stream = #stream_socket_client($host . ':' . $port);
// write HELO command
fwrite($stream, "HELO my.domain.com\r\n");
// read response
$data = '';
while (!feof($stream)) {
$data += fgets($stream, 1024);
}
// repeat for other steps
// ...
// close connection
fclose($stream);
You can just use the build in PHP function mail for it. The body part doesnt have to be just text, it can also contain mixed part data.
Keep in mind that this is a proof of concept. The sendEmlFile function could use some more checking, like "Does the file exists" and "Does it have a boundry set". As you mentioned it is for testing/development, I have not included it.
<?php
function sendmail($body,$subject,$to, $boundry='') {
define ("CRLF", "\r\n");
//basic settings
$from = "Example mail<info#example.com>";
//define headers
$sHeaders = "From: ".$from.CRLF;
$sHeaders .= "X-Mailer: PHP/".phpversion().CRLF;
$sHeaders .= "MIME-Version: 1.0".CRLF;
//if you supply a boundry, it will be send with your own data
//else it will be send as regular html email
if (strlen($boundry)>0)
$sHeaders .= "Content-Type: multipart/mixed; boundary=\"".$boundry."\"".CRLF;
else
{
$sHeaders .= "Content-type: text/html;".CRLF."\tcharset=\"iso-8859-1\"".CRLF;
$sHeaders .= "Content-Transfer-Encoding: 7bit".CRLF."Content-Disposition: inline";
}
mail($to,$subject,$body,$sHeaders);
}
function sendEmlFile($subject, $to, $filename) {
$body = file_get_contents($filename);
//get first line "--Apple-Mail-159-396126150"
$boundry = $str = strtok($body, "\n");
sendmail($body,$subject,$to, $boundry);
}
?>
Update:
After some more testing I found that all .eml files are different. There might be a standard, but I had tons of options when exporting to .eml. I had to use a seperate tool to create the file, because you cannot save to .eml by default using outlook.
You can download an example of the mail script. It contains two versions.
The simple version has two files, one is the index.php file that sends the test.eml file. This is just a file where i pasted in the example code you posted in your question.
The advanced version sends an email using an actual .eml file I created. it will get the required headers from the file it self. Keep in mind that this also sets the To and From part of the mail, so change it to match your own/server settings.
The advanced code works like this:
<?php
function sendEmlFile($filename) {
//define a clear line
define ("CRLF", "\r\n");
//eml content to array.
$file = file($filename);
//var to store the headers
$headers = "";
$to = "";
$subject = "";
//loop trough each line
//the first part are the headers, until you reach a white line
while(true) {
//get the first line and remove it from the file
$line = array_shift($file);
if (strlen(trim($line))==0) {
//headers are complete
break;
}
//is it the To header
if (substr(strtolower($line), 0,3)=="to:") {
$to = trim(substr($line, 3));
continue;
}
//Is it the subject header
if (substr(strtolower($line), 0,8)=="subject:") {
$subject = trim(substr($line, 8));
continue;
}
$headers .= $line . CRLF;
}
//implode the remaining content into the body and trim it, incase the headers where seperated with multiple white lines
$body = trim(implode('', $file));
//echo content for debugging
/*
echo $headers;
echo '<hr>';
echo $to;
echo '<hr>';
echo $subject;
echo '<hr>';
echo $body;
*/
//send the email
mail($to,$subject,$body,$headers);
}
//initiate a test with the test file
sendEmlFile("Test.eml");
?>
You could start here
http://www.dreamincode.net/forums/topic/36108-send-emails-using-php-smtp-direct/
I have no idea how good that code is, but it would make a starting point.
What you are doing is connecting direct to port 25 on the remote machine, as you would with telnet, and issuing smtp commands. See eg http://www.yuki-onna.co.uk/email/smtp.html for what's going on (or see Jasper N. Brouwer's answer).
Just make a quick shell script which processes a directory and call it when you want e.g. using at crontab etc
for I in ls /mydir/ do cat I | awk .. | sendmail -options
http://www.manpagez.com/man/1/awk/
You could also just talk to the mail server using the script to send the emls with a templated body..
Edit: I have added the code to Github, for ease of use by other people. https://github.com/xrobau/smtphack
I realise I am somewhat necro-answering this question, but it wasn't answered and I needed to do this myself. Here's the code!
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
class SMTPHack
{
private $phpmailer;
private $smtp;
private $from;
private $to;
/**
* #param string $from
* #param string $to
* #param string $smtphost
* #return void
*/
public function __construct(string $from, string $to, string $smtphost = 'mailrx')
{
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->SMTPAutoTLS = false;
$mail->Host = $smtphost;
$this->phpmailer = $mail;
$this->from = $from;
$this->to = $to;
}
/**
* #param string $helo
* #return SMTP
*/
public function getSmtp(string $helo = ''): SMTP
{
if (!$this->smtp) {
if ($helo) {
$this->phpmailer->Helo = $helo;
}
$this->phpmailer->smtpConnect();
$this->smtp = $this->phpmailer->getSMTPInstance();
$this->smtp->mail($this->from);
$this->smtp->recipient($this->to);
}
return $this->smtp;
}
/**
* #param string $data
* #param string $helo
* #param boolean $quiet
* #return void
* #throws \PHPMailer\PHPMailer\Exception
*/
public function data(string $data, string $helo = '', bool $quiet = true)
{
$smtp = $this->getSmtp($helo);
$prev = $smtp->do_debug;
if ($quiet) {
$smtp->do_debug = 0;
}
$smtp->data($data);
$smtp->do_debug = $prev;
}
}
Using that, you can simply beat PHPMailer into submission with a few simple commands:
$from = 'xrobau#example.com';
$to = 'fred#example.com';
$hack = new SMTPHack($from, $to);
$smtp = $hack->getSmtp('helo.hostname');
$errors = $smtp->getError();
// Assuming this is running in a phpunit test...
$this->assertEmpty($errors['error']);
$testemail = file_get_contents(__DIR__ . '/TestEmail.eml');
$hack->data($testemail);

Categories