CakePHP : Add “List-Unsubscribe” in email header using Email component - php

I am usign cakephp 2.x and using Email components to send email.
I am trying to add List-Unsubscribe at headers.
$this->Email->headers = [
'List-Unsubscribe'=>'<mailto:'.$email_from.'?subject=Remove from Mailing List>, <'.$SITEURL.'unsubscribe?em='.$email_to.'>',
'List-Unsubscribe-Post'=>'List-Unsubscribe=One-Click'
];
Now in email source its showing in X-header.
X-List-Unsubscribe: <mailto:clients#example.com?subject=Remove from Mailing List>, <http://example.com/unsubscribe?em=xyz#example.com>
X-List-Unsubscribe-Post: List-Unsubscribe=One-Click
But it's not showing Unsubscribe link with From.
I need List-Unsubscribe in message header to avoid spam email.
When i try to use $this->Email->additionalParams its not showing List-Unsubscribe in email header.
Here is code that i am using
$send_from = $email_from_name . "<" . $email_from . ">";
$this->Email->sendAs = 'both'; // text / html / both
$this->Email->from = $send_from;
$this->Email->replyTo = $email_from;
$this->Email->return = $email_from;
$this->Email->to = $email_to;
$this->Email->delivery = 'smtp';
$this->Email->smtpOptions = ['host'=>$imap_server,'port'=>587,'username'=>$email,'password'=>$password];
$this->Email->subject = $subject;
$this->Email->headers = [
'List-Unsubscribe'=>'<mailto:'.$email_from.'?subject=Remove from Mailing List>, <'.SITEURL.'unsubscribe?em='.$email_to.'>',
'List-Unsubscribe-Post'=>'List-Unsubscribe=One-Click' ];
$this->Email->textMessage = $this->_html_to_text($content);
//$this->Email->delivery = 'debug';
$this->Email->send($content);

The email component doesn't support custom non X-prefixed headers, if you need that you'll have to use CakeEmail, which by default doesn't prefix headers, and requires you to explicitly pass prefixed headers in case required.
Given that the email component is long deprecated, ever since the first release of CakePHP 2 to be specific, now is probably a good time for you to finally drop it.
Quick and dirty example:
App::uses('CakeEmail', 'Network/Email');
// The transport/connection configuration should probably better be moved into a config file
$Email = new CakeEmail(array(
'transport' => 'Smtp',
'host' => $imap_server,
'port' => 587,
'username' => $email,
'password' => $password
));
$Email
->emailFormat('both')
->template('subscribe')
->from($send_from)
->replyTo($email_from)
->returnPath($email_from)
->to($email_to)
->subject($subject)
->addHeaders(array(
'List-Unsubscribe' =>
'<mailto:' . $email_from . '?subject=Remove from Mailing List>, ' .
'<' . $SITEURL . 'unsubscribe?em=' . $email_to . '>',
'List-Unsubscribe-Post' => 'List-Unsubscribe=One-Click'
))
->send($content);
This would require two templates, one for HTML in app/View/Emails/html/subscribe.ctp:
<?php
// $content contains the data passed to the `send()` method, wrapped to max 998 chars per line
echo $content;
and one for text in app/View/Emails/text/subscribe.ctp, requiring you to move the HTML to text conversion into the template. You should probably make it a helper, the following should just illustrate the principle:
<?php
echo _html_to_text($content);
See also
Cookbook > Core Libraries > Utilities > CakeEmail > Configuration
Cookbook > Core Libraries > Utilities > CakeEmail > Sending templated emails

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.

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

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.

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.

Why it takes so long to send multiple emails with Sendgrid?

I have a sport betting tips website and on every tip that i publish i send an email to every user (about 700 users in total) with SendGrid. The problem comes with the delivery time. The email is delayed even half an hour from the time of send.
Does anyone know why and how could i fix it?
I am sending it with SMTP.
Here is some of my code:
$catre = array();
$subiect = $mailPronostic['subiect'];
$titlu = $mailPronostic['titlu'];
$text = $mailPronostic['text'];
$data = new DateTime($this->_dataPronostic);
foreach($users as $user){
array_push($catre, $user->_emailUser);
}
$data = urlencode($data->format("d-m-Y H:i"));
$echipe = urlencode($this->_gazdaPronostic." vs ".$this->_oaspetePronostic);
$pronostic = urlencode($predictii[$this->_textPronostic]);
$cota = $this->_cotaPronostic;
$mesaj = file_get_contents("http://plivetips.com/mailFiles/mailPronostic.php?text=".urlencode($text)."&titlu=".urlencode($titlu)."&data=$data&echipe=$echipe&pronostic=$pronostic&cota=$cota");
//return mail(null, $subiect, $mesaj, $header);
$from = array('staff#plivetips.com' => 'PLIVEtips');
$to = $catre;
$subject = "PLIVEtips Tip";
$username = 'user';
$password = 'pass';
$transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 587);
$transport->setUsername($username);
$transport->setPassword($password);
$swift = Swift_Mailer::newInstance($transport);
$message = new Swift_Message($subject);
$message->setFrom($from);
$message->setBody($mesaj, 'text/html');
$numSent = 0;
foreach ($to as $address => $name)
{
if (is_int($address)) {
$message->setTo($name);
} else {
$message->setTo(array($address => $name));
}
$numSent += $swift->send($message, $failures);
}
Thx.
how long does the script take to run? I have a feeling the script is taking a long time. If that's the case, I think it is because you are opening a connection for each message.
With SendGrid, you can send a message to 1000 recipients with one connection by using the X-SMTPAPI header to define the recipients. The easiest way to do this to use the official sendgrid-php library and use the setTos method.
Recipients added to the X-SMTPAPI header will each be sent a unique email. Basically SendGrid's servers will perform a mail merge. It doesn't look like your email content varies with each user, but if it does, then you may use substitution tags in the header to specify custom data per recipient.
If you don't want to use sendgrid-php, you can see how to build the header in this example.

Sending mass email SLOW with PHP PEAR Mail and ALT-N Mdaemon pro

We have a growing mailing list which we want to send our newsletter to. At the moment we are sending around 1200 per day, but this will increase quite a bit. I've written a PHP script which runs every half hour to send email from a queue. The problem is that it is very slow (for example to send 106 emails took a total of 74.37 seconds). I had to increase the max execution time to 90 seconds to accomodate this as it was timing out constantly before. I've checked that the queries aren't at fault and it seems to be specifically the sending mail part which is taking so long.
As you can see below I'm using Mail::factory('mail', $params) and the email server is ALT-N Mdaemon pro for Windows hosted on another server. Also, while doing tests I found that none were being delivered to hotmail or yahoo addresses, not even being picked up as junk.
Does anyone have an idea why this might be happening?
foreach($leads as $k=>$lead){
$t1->start();
$job_data = $jobObj->get(array('id'=>$lead['job_id']));
$email = $emailObj->get($job_data['email_id']);
$message = new Mail_mime();
//$html = file_get_contents("1032.html");
//$message->setTXTBody($text);
$recipient_name = $lead['fname'] . ' ' . $lead['lname'];
if ($debug){
$email_address = DEBUG_EXPORT_EMAIL;
} else {
$email_address = $lead['email'];
}
// Get from job
$to = "$recipient_name <$email_address>";
//echo $to . " $email_address ".$lead['email']."<br>";
$message->setHTMLBody($email['content']);
$options = array();
$options['head_encoding'] = 'quoted-printable';
$options['text_encoding'] = 'quoted-printable';
$options['html_encoding'] = 'base64';
$options['html_charset'] = 'utf-8';
$options['text_charset'] = 'utf-8';
$body = $message->get($options);
// Get from email table
$extraheaders = array(
"From" => "Sender <sender#domain.com>",
"Subject" => $email['subject']
);
$headers = $message->headers($extraheaders);
$params = array();
$params["host"] = "mail.domain.com";
$params["port"] = 25;
$params["auth"] = false;
$params["timeout"] = null;
$params["debug"] = true;
$smtp = Mail::factory('mail', $params);
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
$logObj->insert(array(
'type' => 'process_email',
'message' => 'PEAR Error: '.$mail->getMessage()
));
$failed++;
} else {
$successful++;
if (DEBUG) echo("<!-- Message successfully sent! -->");
// Delete from queue
$deleted = $queueObj->deleteById($lead['eq_id']);
if ($deleted){
// Add to history
$history_res = $ehObj->create(array(
'lead_id' => $lead['lead_id'],
'job_id' => $lead['job_id']
)
);
if (!$history_res){
$logObj->insert(array(
'type' => 'process_email',
'message' => 'Error: add to history failed'
));
}
} else {
$logObj->insert(array(
'type' => 'process_email',
'message' => 'Delete from queue failed'
));
}
}
$t1->stop();
}
hard to tell. You should profile your code using xdebug to pintpoint low hanging fruit.
Also I think you might consider using a message queue to process your e-mail(redis/beanstalkd/gearmand/kestrel) asynchronous or using third-party dependency like for example google app engine which is very cheap($0.0001 per recipient/first 1000 emails a day free)/reliable. That will cost you about 10 cent a day when considering your load.
you're facing a couple of different problems.
1.) to send a lot of emails you really need a mailer queue and several mail servers to get mail from that queue and process the mail in turn (round robin style <-- this link is related but not perfectly specific to your needs. [It's enough to get you started]).
2.) your mail is likely not getting to Hotmail/yahoo for one of 2 reasons.
a.) you don't have RDNS properly configured and when the look for your IP (from the heder) it is not mapping back right to your domain in the header. or
b.), you've already been flagged as a spammer on SPAMHAUS or whatever the blacklisting service du jour is.

Categories