Use html file as body of Zend mail\message - php

Not sure what's the syntax of having html files rendered when added to Zend\Mail\Message?
Here's a piece of code I have:
$mail = new Mail\Message();
$html = file_get_contents('content.html');
$mail->setBody($html);
Is it sufficient to set it up like this or do I need to specify the type of content somehow?
Thanks.

You can attach it as a Mime part.
Example from the docs:
use Zend\Mail\Message;
use Zend\Mime\Message as MimeMessage;
use Zend\Mime\Part as MimePart;
$html = new MimePart($htmlMarkup);
$html->type = "text/html";
$body = new MimeMessage();
$body->setParts(array($text, $html, $image));
$message = new Message();
$message->setBody($body);

Related

Send PhpWord file as email attachment

What is the correct way to generate an email attachment with PhpWord?
I tried multiple ways but I get a corrupt file with size 1kb. If I trigger a download of the file instead, the file is OK.
$fileName = 'file.docx';
$fileAttachment = tempnam(sys_get_temp_dir(), 'PHPWord');
$template->saveAs($fileAttachment);
$contentType = "application/octet-stream";
$notification
->setTemplate("template", $templateParams)
->setSubject($this->_("Email subject"))
->addRecipient("to", $email, $email)
->addAttachment($fileName, $fileAttachment, $contentType);
What am I doing wrong?
Thank you!
You could try to use file_get_contents function to read the contents of the file and then pass it as the second parameter to the addAttachment() method:
$fileAttachmentContent = file_get_contents($fileAttachment);
$notification
->setTemplate("template", $templateParams)
->setSubject($this->_("Email subject"))
->addRecipient("to", $email, $email)
->addAttachment($fileName, $fileAttachmentContent, $contentType);
PHPWord is for generating Word documents, but it does not send mails.
You can combine it with any PHP mailer library. This is a sample on how to do it using SwitfMailer:
<?php
require_once '[...]/phpword/src/PhpWord/Autoloader.php';
require_once '[...]/swiftmailer/lib/swift_required.php';
// create a new document with phpWord
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$text = $section->addText("Here your text...");
// Use Swift Mailer to create an attachment object...
$attachment = new Swift_Attachment(
$phpWord->save(),
'file.docx',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
);
// ...and send the email
$transport = Swift_SmtpTransport::newInstance('smtp.yoursmtp.com', 25);
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Here your subject')
->setFrom(['sender#sdomain.net' => 'Sender Name'])
->setTo(['receiver#rdomain.org' => 'Receiver Name'])
->setBody('Here the body message...')
->attach($attachment);
$result = $mailer->send($message);
You can use any other mail library you like. Or even use the PHP mail() function, but is more tricky to set the mail headers properly.

Laminas-mail. send as UFT8

I work with Laminas (former Zendframework 3). I want to send a mail with Laminas-Mail. I dont know how to change the Content-Type. Currently it is Content-Type: text/html but I want to send UTF8 mails, so therefore I want to use Content-Type: text/html; charset=utf-8.
I tried to change $html->type but I failed.
use Laminas\Mail;
use Laminas\Mail\Transport\Smtp as SmtpTransport;
use Laminas\Mail\Transport\SmtpOptions;
use Laminas\Mime\Message as MimeMessage;
use Laminas\Mime\Part as MimePart;
# ...
# much code
# ...
// Produce HTML
$bodyHtml = $this->viewRenderer->render('mymodule/email/email1');
$html = new MimePart($bodyHtml);
$html->type = "text/html; charset=utf-8"; #Seems not to work
$body = new MimeMessage();
$body->addPart($html);
$mail = new Mail\Message();
$mail->setEncoding('UTF-8');
$mail->setBody($body);
$mail->setFrom('bobafit#example.com','Boba Fit');
$mail->addTo('bobafit#example.com','Boba Fit');
$mail->setSubject('Thank you for reading my Question');
// Setup SMTP transport
$transport = new SmtpTransport();
$options = new SmtpOptions($this->config['smtp']);
$transport->setOptions($options);
$transport->send($mail);
Please check the official Dok:
https://docs.laminas.dev/laminas-mail/message/attachments/
Type and charset are defined separatly.
You are probably looking for something like that:
$html = new MimePart($htmlMarkup);
$html->type = Mime::TYPE_HTML;
$html->charset = 'utf-8';

How can I attach a view/pdf/xml in an Email? Symfony2

I want to send and email like this:
$message = \Swift_Message::newInstance()
->setSubject('bla bla')
->setFrom('example#gmail.com')
->setTo('example#gmail.com')
->setCharset('UTF-8')
->setContentType('text/html')
->setBody("hi");
$this->getContainer()->get('mailer')->send($message);
$output->writeln('sent!');
However, I want attach a generate template like this:
$template = $this->getContainer()->get('templating');
$xml = $template->render("MrLibrariesReportsBundle:Transactions:download.xml.twig", $viewData);
I tried to do:
$message->attach($xml);
But it doesnt work.
What can I do?
Thanks!
Something like this:
$message = \Swift_Message::newInstance()
->setSubject('Subject')
->setFrom('From')
->setTo('To')
->setBody($this->container->get('templating')->render(
'AppBundle:Mail:welcome.html.twig', $viewData),
'text/html'
);
$this->container->get('mailer')->send($message);
I resolve it. I did the next code:
$message = \Swift_Message::newInstance()
->setSubject('bla bla')
->setFrom('example#gmail.com')
->setTo('example#gmail.com')
->setCharset('UTF-8')
->setContentType('text/html')
->setBody("hi")
->attach(\Swift_Attachment::fromPath($attach));
$this->getContainer()->get('mailer')->send($message);
$output->writeln('sent!');
$attach is the patch of file or in this case is the render of template:
$template = $this->getContainer()->get('templating');
$xml = $template->render("MrLibrariesReportsBundle:Transactions:download.xml.twig", $viewData);
$attach == $xml
The most important is:
\Swift_Attachment::

Interpret string as HTML in PHP

i am working on PHP, and i've only just begun, so i would like to ask some advice on something i can't quite seem to find online.
I have a PHP-file that gets 2 strings: A name and a lot of HTML-text.
$name = $_POST['name'];
$content = $_POST['content'];
Now i want to use those 2 to create a new HTML file and save it. So far i've managed to make it save a new HTML file and use the name as the <title> tag. Now what i want is to do is replace the (currently empty) body with my HTML string, interpreted as HTML.
This builds my body tag:
$body = $doc->createElement('body');
$body = $root->appendChild($body);
Now i found 2 ways to do this, and both don't work:
Solution 1:
$content = $doc->createTextNode($content);
$content = $body->appendChild($content);
This inserts my HTML into my body, but it parses literally as '<div id="lala">content</div>'. So this isn't what i want.
Solution 2:
$content = $doc->loadHTML($content);
This actually makes the html load as HTML, but now it replaces my entire HTML and things like adding css and js to the head will now actually go UNDER the new body, instead of in the head. As such:
$link_1 = $doc->createElement('link');
$link_1->setAttribute('rel','stylesheet');
$link_1->setAttribute('href','css/mystylesheet.min.css');
$link_1 = $head->appendChild($link_1);
So basically i want to both interpret my string as HTML, AND make it load in the correct place. I've tried to change it to $body->loadHTML($content), but this gives me an internal error.
Does anyone know the PHP-method i'm looking for? Thanks!
This will work. Let me know if you need explanation :)
<?php
ini_set( 'display_errors', 1 );
ini_set( 'error_reporting', E_ALL );
$dom = new DOMDocument( '1.0' );
$dom->formatOutput = true;
$dom->preserveWhiteSpace = true;
// test values
$name = 'Test';
$content = '<div onclick="alert(\'Hello!\');">Test div</div>';
// create <html>, <head>, <title> and <body> tags
$html = $dom->createElement( 'html' );
$head = $dom->createElement( 'head' );
$title = $dom->createElement( 'title' );
$body = $dom->createElement( 'body' );
// title text
$titleText = $dom->createTextNode( $name );
// import the text in a new dom
$dom1 = new DOMDocument( '1.0' );
$dom1->formatOutput = true;
$dom1->preserveWhiteSpace = true;
$bodyText = $dom1->loadHTML( $content );
$bodyText = $dom1->getElementsByTagName('body')->item(0);
// add them to the dom
$html = $dom->appendChild( $html );
$html->appendChild( $head );
$head->appendChild( $title );
$title->appendChild( $titleText );
$html->appendChild( $body );
$bodyT = $dom->importNode( $bodyText, true );
$body->appendChild( $bodyT );
echo $dom->saveHTML();
?>
Hope this helps.
Of course, the text in createTextNode stands for plain text (vs. HTML).
Fatal error: Call to undefined method DOMElement::loadHTML()
Correct, loadHTML() belongs to DOMDocument, not DOMElement. In your case, the document is apparently $doc (not $body). So you need to call:
$doc->loadHTML()

Swift Mailer attachments

I'm creating a CSV on the fly with PHP, I then need to attach this CSV file to the the Swift Mailer Message. I have tried using file_get_content on the created file aswell as using chunk_split(base64_encode(file_get_contents()) on the created file aswell as attaching the file before writing it to disk. Without writing to disk I get Rescource #183 in the CSV, with attaching it with file_get_content I get just a string in each row of the CSV file, anyone know what I'm doing wrong?
if(!file_exists(_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv'))
{
if($file = fopen (_PS_ORDERS_DIR_.$orderDate.'/'.$file_name.'.csv', 'x+'))
{
foreach ($list as $fields)
{
fputcsv($file, $fields);
}
$attachment['mime'] = 'application/vnd.ms-excel';
$attachment['content'] = file_get_contents($file);
$attachment['name'] = $order.'order';
EDIT
Mail::Send(1, 'order_conf', 'Order CSV Attachment', $success, 'test#email.com', Address, NULL, NULL, $attachment); // attach and send
}
}
Attaching a file into a swift mailer:
$swift =& new Swift(new Swift_Connection_SMTP(MAIL_SMTP_URL, MAIL_SMTP_PORT));
$message =& new Swift_Message($subject);
$recpients =& new Swift_RecipientList();
$sender =& new Swift_Address('info#example.com', 'example.com');
$recpients->addTo('info#example.com', 'www.example.com');
$message->attach(new Swift_Message_Part('this is my body'));
$message->attach(new Swift_Message_Attachment($binarycontents, $fileTitle, $mimeType));
$swift->send($message, $recpients, $sender);
in your case the attaching would be:
$message->attach(new Swift_Message_Attachment(file_get_contents($file), $order.'order.csv', 'application/vnd.ms-excel'));
just for example ofcourse :)
//to set headers of csv file(first row)
$content = "user_id,first_name,last_name,phone,gender,pan_number\r\n";
//this can be dynamic data from database or from anywhere can loop this for multiple rows
$content .= "1,test_fn,test_ln,8888999900,M,ASDD3333\r\n";
//include swiftmailer library in order to run the below code
Yii::$app->mailer->compose()
->setFrom(array('test#test.com'=>'test'))
->setTo('testto#testto.com')
->setSubject('your subject' )
->setHtmlBody('<table><tr><td>your email body message here</td></tr> </table>')
->attachContent($content, ['fileName' => 'user.csv', 'contentType' => 'application/vnd.ms-excel'])->send();

Categories