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

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();
}

Related

Why am i getting this error when trying to send email for activation of new user account with phpmailer

i am trying to understand why my subject method in index.php triggers an error of not being defined.i am using phpmailer 5.2.7 with php 7.2 and wampserver 3.1.7
//here is my extended class from phpmailer//
<?php
include('phpmailer.php');
class Mail extends PhpMailer
{
// Set default variables for all new objects
public $From = 'xxxxxx#gmail.com';
public $FromName = MM;
public $Host = 'smtp.gmail.com';
public $Mailer = 'smtp';
public $SMTPAuth = true;
public $Username = 'xxxxxxx#gmail.com';
public $Password = 'xxxxxx';
public $SMTPSecure = 'ssl';
public $WordWrap = 75;
public function subject($subject)
{
$this->Subject = $subject;
}
public function body($body)
{
$this->Body = $body;
}
public function send()
{
$this->AltBody = strip_tags(stripslashes($this->Body))."\n\n";
$this->AltBody = str_replace(" ", "\n\n", $this->AltBody);
return parent::send();
}
}
and here is part of my index page where i have defined my variables
$to = $_POST['email'];
$subject = "Registration Confirmation";
$body = "<p>Thank you for registering at demo site.</p>
<p>To activate your account, please click on this link: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>
<p>Regards Site Admin</p>";
$mail = new PHPMailer(true);
$mail->setFrom(SITEEMAIL);
$mail->addAddress($to);
$mail->subject($subject);
$mail->body($body);
$mail->send();
//redirect to index page
header('Location: index.php?action=joined');
exit;
Firstly, why are you using a version of PHPMailer that's literally years out of date? Get the latest, which has new features, fixed bugs, and fewer security holes. While you're upgrading, consider switching to using composer to manage your dependencies.
The problem you're having is quite straightforward: you have created a subclass that adds the subject() method, but the instance you've created in your script is of the original PHPMailer class, not your subclass. Do this instead:
$mail = new Mail(true);
Naming your class with a very generic "Mail" name is very likely to bring you an unexpected lesson on why namespacing is a good idea, so I'd recommend adding a namespace for your app to avoid name clashes.
While it's a good idea to subclass like this to set default values easily, it's also inviting you to check in credentials to your source repo, which is usually a bad idea. Better to use your child class to read those values from an environment file ("dot env") using a package like this.

Symfony, swiftmailer, incorrect email

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');

How can I set default setFrom in Zend_Mail

How can I set the default setFrom field with title in Zend_Mail
If I send mail like this
public function sendActivationEmail($id) {
$mail = new Zend_Mail();
$mail ->addTo('emailId1#gmail.com',"Recepient Name")
->setFrom("emailId1#gmail.com","Site Name")
->setSubject("My Subject")
->setBodyText("Some body msg")
->setBodyHtml("Some body msg")
->send();
}
I get an email in nice format with From Field in mail as "Site Name"
But If I send mail without setFrom, I still get the mail, but the title is "emailId1#gmail.com". I dont want to use SetFrom() just to get "Site From". Is there a way I can set it so that "Site Name" gets picked up by default ?
I have followed this tutorial for setting up my email : http://www.zendcasts.com/introduction-to-zend_mail/2010/02/
Thank you,
If you want to set a default email address for the from attribute, you can use setDefaultFrom() static method like this:
For example, in your boostrap:
protected function _initFromMail(){
// You can get the mail from an init file
Zend_Mail::setDefaultFrom('emailId1#gmail.com', 'Site Name');
}
In your function, the from adress mail is automatically fiiled.
public function sendActivationEmail($id) {
$mail = new Zend_Mail();
$mail ->addTo('emailId1#gmail.com',"Recepient Name")
->setSubject("My Subject")
->setBodyText("Some body msg")
->setBodyHtml("Some body msg")
->send();
}
I would probably just create a subclass of Zend_Mail and use that. Something like the following:
class My_Mail extends Zend_Mail
{
public function __construct($charset = null)
{
parent::__construct($charset);
setFrom('emailId1#gmail.com, 'Site Name');
}
}
Then usage would be:
$mail = new My_Mail();
$mail ->addTo('emailId1#gmail.com','Recipient Name')
->setSubject('My Subject')
->setBodyText('Some body msg')
->setBodyHtml('Some body msg')
->send();
The usual requirements about how to autoload classes in the My_ pseudo-namespace would apply. For example, you could add:
autoloaderNamespaces[] = My_
to your application/config/application.ini

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?

How to send mail using cake php and where to start?

I wanna try to send mail using cake php. I have no experience of sending mail. So, I don't know where to start. Is it need to make mail server? If need, how to make mail server and how to send mail? Please explain step by step. I really don't know where to start.
I'm using xampp and now I test my site at localhost.
I tested following link:
http://book.cakephp.org/view/1286/Sending-a-basic-message
but error occurred cannot be accessed directly.
and then I add code from the following link:
http://book.cakephp.org/view/1290/Sending-A-Message-Using-SMTP
So, my code is following:
function _sendMail(){
$this->Email->to = 'user#gmail.com';
$this->Email->bcc = array('secret#example.coom');
$this->Email->subject = 'Welcome to our really cool things';
$this->Email->replyTo = 'support#example.com';
$this->Email->from = 'Online Application <app#example.coom>';
$this->Email->template = 'simple_message';
$this->Email->sendAs = 'both';
$this->Email->smtpOptions = array(
'port' =>'25',
'timeout' => '30',
'host' => 'ssl://smtp.gmail.com',
'username' => 'my_mail#gmail.com',
'password' =>'aaa',
);
$this->Email->delivery = 'smtp';
$this->Email->send();
}
but error still occurred. But, I didn't make any mail server.Is that OK?
I have a feeling this is to do with your XAMPP configuration:
Try opening "php.ini", it should be somewhere in your server files.
Search for the attribute called “SMTP” in the php.ini file.Generally you can find the line “SMTP=localhost“. change the localhost to the smtp server name of your ISP. And, there is another attribute called “smtp_port” which should be set to 25.I’ve set the following values in my php.ini file.
SMTP = smtp.wlink.com.np
smtp_port = 25
Restart the apache server so that PHP modules and attributes will be reloaded.
ow try to send the mail using the mail() function:
mail(“you#yourdomain.com”,”test subject”,”test body”);
If you get the following warning:
Warning: mail() [function.mail]: “sendmail_from” not set in php.ini or custom “From:” header missing in C:\Program Files\xampp\htdocs\testmail.php on line 1
Specify the following headers and try to send the mail again:
$headers = ‘MIME-Version: 1.0′ . “\r\n”;
$headers .= ‘Content-type: text/html; charset=iso-8859-1′ . “\r\n”;
$headers .= ‘From: sender#sender.com’ . “\r\n”;
mail(“you#yourdomain.com”,”test subject”,”test body”,$headers);
source: http://roshanbh.com.np/2007/12/sending-e-mail-from-localhost-in-php-in-windows-environment.html
Naming the controller function with a leading underscore is Cake's backwards compatible way of designating that the function should be protected, i.e. that the function should not be accessible as a normal controller action. That means you can't access FooController::_sendMail() using the URL /foo/_sendMail, or any other URL for that matter. You should be seeing this, which IMO is a pretty good error message:
Private Method in UsersController
Error: FooController::_sendMail() cannot be accessed directly.
Remove the leading underscore, that's all. This problem has nothing to do with sending email.
Try:
//load mail component in controller
var $components = array('Mail');
//then do
$this->Email->sendAs="html";
$this->Email->from="some#domain.com";
$this->Email->to="someone#domain.com";
$this->Email->subject="Your subject;
$this->Email->send("Your message);
//Check cakephp manual for more reference: http://book.cakephp.org/
Here is an example code for sending an HTML email with CakePHP's Email component
Ex controller : EmailController.php
<?php
class EmailController extends AppController{
public $components=array('Email');
function send(){
//create an array of values to be replaced in email html template//
$emailValues=array('name'=>'MyName','phone'=>'MyPhone');
$this->set('emailValues',$emailValues);//pass to template //
$this->Email->to = 'to#address.com'; //receiver email id
$this->Email->subject = 'Subject Line';
$this->Email->replyTo = 'reply#address.com'; //reply to email//
$this->Email->from = 'SenderName<sender#address.com>'; //sender
$this->Email->template = 'sample';//email template //
$this->Email->sendAs = 'html';
if($this->Email->send()){
//mail send //
}
}
?>
Now create the email template in folder /Views/Email/html/
ie the template path should be
/Views/Email/html/sample.ctp
sample.ctp
<?php
Hi <?php echo $emailValues['name'];?> <br>
Thanks for sharing your phone number '<?php echo $emailValues['phone'];?>' .
<br>
?>

Categories