Symfony, swiftmailer, incorrect email - php

I use swift mailer for send email, and after send email in box I have mail without html, like in screen
but in another mail services everything fine
this my code
public function createMessage($subject, $receivers, $template, $context)
{
$message = \Swift_Message::newInstance($subject);
$message->setFrom($this->from_address);
$message->setTo($receivers);
$body = $this->twig->render($template, $context);
$plaintext = strip_tags($body);
$message->setBody($body, "text/html");
$message->addPart($plaintext, "text/plain");
$this->mailer->send($message);
}
What problem in this code? I set body test/html. What problem not understand

Try with this:
public function __construct(Container $oContainer) {
$this->oContainer = $oContainer;
}
$this->oContainer->get('templating')->render()
And set the content yourself:
$message->setContentType('text/html');

Related

Swiftmailer pdf attachment from snappy bundle

I have an function downloadPdf($id, \Knp\Snappy\Pdf $snappy, Request $request).
This function downloads a pdf with information from objects everything works fine.
This is the function:
public function downloadPdf($id, \Knp\Snappy\Pdf $snappy, Request $request): Response
{
//search id
$workOrder = $this->getDoctrine()->getRepository(WorkOrders::class)->find($id);
//data to pdf template
$html = $this->renderView('pdf/pdf.html.twig', array(
'workOrder' => $workOrder,
));
//name file
$filename = $workOrder->getId();
//download pdf
return new PdfResponse(
$snappy->getOutputFromHtml($html),
$filename.'.pdf'
);
}
And then I have an swift mailer function:
//check if signed and if check is true
if ($data_uri) {
//send workOrder to company
if ($check == true) {
$transport = (new \Swift_SmtpTransport('smtp.sendgrid.net', 587))
->setUsername('sendgridUSERNAME')
->setPassword('sendgridPASSWORD')
;
$mailer = new \Swift_Mailer($transport);
$message = (new \Swift_Message('Werkbon '.$workOrder->getTitel()))
->setFrom(['xxx' => 'xxx'])
->setTo('xxx')
->setBody('xxx')
->attach(\Swift_Attachment::fromPath($this->downloadPdf()))
;
$result = $mailer->send($message);
}
The email works fine but I want to attach the pdf from the other function to this email in the code above you can see what I tried but I think I got it totally wrong.
I have no idea where to start.
Can someone give me a little push in the right direction?
Thanks!
here is how it works for me,
$invoicepdf = $this->get('knp_snappy.pdf')->getOutputFromHtml($html);
/* And instead of returning pdf, send it with mailer: */
$message = \Swift_Message::newInstance()
->setSubject('YOUR_TITLE')
->setFrom('foo#from.net')
->setTo('foo#to.net')
->attach(\Swift_Attachment::newInstance($invoicepdf, 'your_file_name','application/pdf'))
->setBody("yyy");
$mailer->send($message);

Unable to move mails to sent folder of IMAP using Laravel

I am sending emails from my laravel website using SMTP. When i send email to the user then i want to copy that mail to IMAP sent folder too.
Here is my code when i am sending mail to user:
$mail = Mail::to($this->receiver)
->send(new ComplaintMail($this->sender->user_email,$this->subject,$this->complaint,$this->answers,$this->sender));
$path = "{mypath.com:993/imap/ssl}Sent";
$imapStream = imap_open($path,$this->sender->user_email,$this->sender->email_password);
$result = imap_append($imapStream,$path,$mail->getSentMIMEMessage());
imap_close($imapStream);
Also I tried using imap_mail_move() method like so:
$mail = Mail::to($this->receiver)
->send(new ComplaintMail($this->sender->user_email,$this->subject,$this->complaint,$this->answers,$this->sender));
$path = "{mypath.com:993/imap/ssl}Sent";
$imapStream = imap_open($path,$this->sender->user_email,$this->sender->email_password);
imap_mail_move($imapStream,$mail,$path);
imap_close($imapStream);
Both ways it didn't worked out
In ComplaintMail class, build function looks like :
public function build()
{
return $this->from($this->sender)
->subject($this->subject)
->markdown('emails.complaint');
}

How to send html page as message when sending email in codeigniter?

I want to send a html page as message when sending email in codeigniter..
$this->email->set_mailtype("html");
$this->email->from('xyz#gmail.com', 'ABC');
$this->email->to($this->input->post('emailid'));
$this->email->subject('New Subject');
$message = //HERE I WANT TO INCLUDE A FILE TO END AS MESSAGE
$this->email->message($message);
$this->email->send();
Could it be possible ??
Please help...
You can simply use the method file_get_contents()
$message = file_get_contents("/path/to/htmlfile");
Also you can use the codeigniter way
$template = $this->load->view(APPATH.'email/file', $your_data, true);
What I have been using in my project, I created a function in a common_helper named as sendMail
function sendMail($subject, $mailContent, $mailTo, $mailFromId, $mailFromName)
{
$CI =& get_instance();
$CI->load->library('email');
$config['charset'] = 'utf-8';
$config['wordwrap'] = TRUE;
$config['mailtype'] = 'html';
$CI->email->clear(TRUE);
$CI->email->initialize($config);
$CI->email->from($mailFromId, $mailFromName);
$CI->email->to($mailTo);
$CI->email->subject($subject);
$CI->email->message($mailContent);
$CI->email->send();
}
You can call this function anywhere from your controller to send mail. Regarding HTML content of email should be loaded as Agam Banga mentioned above:
$mailContent = $this->load->view('email/template', $data, true);
This varibale can be passed simply calling like
sendMail($subject, $mailContent, $mailTo, $mailFromId, $mailFromName);
In your controller.
Let me know if you face any issue.
Here the code of Model and sending mail Using Email Library. And auto load library use it on your config folder -> autoload file
$autoload['libraries'] = array('email');
public function mail_send($mdata){
$this->load->library('email');
$this->email->set_mailtype('html');
//$this->email->set_newline("\r\n");
$this->email->from($mdata['email']); // change it to yours
$this->email->to('xyz#gmail.com');// change it to yours
$this->email->cc($mdata['email']);
$this->email->subject('Hello');
//$this->email->message($mdata['address']);
$body= $this->load->view('pages/mail', $mdata, true);
$this->email->message($body);
// echo '<pre>';
// print_r($mdata);
// exit();
$this->email->send();
$this->email->clear();
}

Is it possible to define the mail's subject inside of the blade template?

When sending a mail using Mail::queue / Mail::send you have to pass a mail template and the subject separately.
Is there a way to manage the subject in the mail templates (better for multi-languages).
I.e. as the first line in the template
mail.blade.php
This is the subject
Hello User,
foobar
It's not that hard:
Mail::queue($template, $data, function (Message $message) use ($toUser, $sendingName, $sendingAddress) {
// take subject from first line of the template
$body = $message->getSwiftMessage()->getBody();
$bodyLines = explode("\n", $body);
if (count($bodyLines) == 0) {
Log::warning('Empty mail');
return;
}
$subject = $bodyLines[0];
unset($bodyLines[0]);
// send
$message->getSwiftMessage()->setBody(implode("\n", $bodyLines));
....

Replace multiple placeholders with PHP?

I have a function that sends out site emails (using phpmailer), what I want to do is basically for php to replace all the placheholders in the email.tpl file with content that I feed it. The problem for me is I don't want to be repeating code hence why I created a function (below).
Without a php function I would do the following in a script
// email template file
$email_template = "email.tpl";
// Get contact form template from file
$message = file_get_contents($email_template);
// Replace place holders in email template
$message = str_replace("[{USERNAME}]", $username, $message);
$message = str_replace("[{EMAIL}]", $email, $message);
Now I know how to do the rest but I am stuck on the str_replace(), as shown above I have multiple str_replace() functions to replace the placeholders in the email template. What I would like is to add the str_replace() to my function (below) and get it to find all instances of [\] in the email template I give it and replace it with the placeholders values that I will give it like this: str_replace("[\]", 'replace_with', $email_body)
The problem is I don't know how I would pass multiple placeholders and their replacement values into my function and get the str_replace("[{\}]", 'replace_with', $email_body) to process all the placeholders I give it and replace with there corresponding values.
Because I want to use the function in multiple places and to avoid duplicating code, on some scripts I may pass the function 5 placeholders and there values and another script may need to pass 10 placeholders and there values to the function to use in email template.
I'm not sure if I will need to use an an array on the script(s) that will use the function and a for loop in the function perhaps to get my php function to take in xx placeholders and xx values from a script and to loop through the placeholders and replace them with there values.
Here's my function that I referred to above. I commented the script which may explain much easier.
// WILL NEED TO PASS PERHAPS AN ARRAY OF MY PLACEHOLDERS AND THERE VALUES FROM x SCRIPT
// INTO THE FUNCTION ?
function phpmailer($to_email, $email_subject, $email_body, $email_tpl) {
// include php mailer class
require_once("class.phpmailer.php");
// send to email (receipent)
global $to_email;
// add the body for mail
global $email_subject;
// email message body
global $email_body;
// email template
global $email_tpl;
// get email template
$message = file_get_contents($email_tpl);
// replace email template placeholders with content from x script
// FIND ALL INSTANCES OF [{}] IN EMAIL TEMPLATE THAT I FEED THE FUNCTION
// WITH AND REPLACE IT WITH THERE CORRESPOING VALUES.
// NOT SURE IF I NEED A FOR LOOP HERE PERHAPS TO LOOP THROUGH ALL
// PLACEHOLDERS I FEED THE FUNCTION WITH AND REPLACE WITH THERE CORRESPONDING VALUES
$email_body = str_replace("[{\}]", 'replace', $email_body);
// create object of PHPMailer
$mail = new PHPMailer();
// inform class to use smtp
$mail->IsSMTP();
// enable smtp authentication
$mail->SMTPAuth = SMTP_AUTH;
// host of the smtp server
$mail->Host = SMTP_HOST;
// port of the smtp server
$mail->Port = SMTP_PORT;
// smtp user name
$mail->Username = SMTP_USER;
// smtp user password
$mail->Password = SMTP_PASS;
// mail charset
$mail->CharSet = MAIL_CHARSET;
// set from email address
$mail->SetFrom(FROM_EMAIL);
// to address
$mail->AddAddress($to_email);
// email subject
$mail->Subject = $email_subject;
// html message body
$mail->MsgHTML($email_body);
// plain text message body (no html)
$mail->AltBody(strip_tags($email_body));
// finally send the mail
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent Successfully!";
}
}
Simple, see strtrĀ­Docs:
$vars = array(
"[{USERNAME}]" => $username,
"[{EMAIL}]" => $email,
);
$message = strtr($message, $vars);
Add as many (or as less) replacement-pairs as you like. But I suggest, you process the template before you call the phpmailer function, so things are kept apart: templating and mail sending:
class MessageTemplateFile
{
/**
* #var string
*/
private $file;
/**
* #var string[] varname => string value
*/
private $vars;
public function __construct($file, array $vars = array())
{
$this->file = (string)$file;
$this->setVars($vars);
}
public function setVars(array $vars)
{
$this->vars = $vars;
}
public function getTemplateText()
{
return file_get_contents($this->file);
}
public function __toString()
{
return strtr($this->getTemplateText(), $this->getReplacementPairs());
}
private function getReplacementPairs()
{
$pairs = array();
foreach ($this->vars as $name => $value)
{
$key = sprintf('[{%s}]', strtoupper($name));
$pairs[$key] = (string)$value;
}
return $pairs;
}
}
Usage can be greatly simplified then, and you can pass the whole template to any function that needs string input.
$vars = compact('username', 'message');
$message = new MessageTemplateFile('email.tpl', $vars);
The PHP solutions can be:
usage of simple %placeholder% replacement mechanisms:
str_replace,
strtr,
preg_replace
use of pure PHP templating and conditional logic (short open tags in PHP and alternative syntax for control structures)
Please, find the wide answer at Programmers.StackExchange to find out other approaches on PHP email templating.
Why dont you just make the email template a php file aswell? Then you can do something like:
Hello <?=$name?>, my name is <?=$your_name?>, today is <?=$date?>
inside the email to generate your HTML, then send the result as an email.
Seems to me like your going about it the hard way?

Categories