I would like to use PHPMailer in my MVC site but the view content doesn't come for the $emailTemplate variable. This is my own MVC. The problem starts here:
$emailTemplate = $this->view('emails/expirityRemainder'); Could somebody tell me how to manage that change?
If I will do that everything works fine, but I need to load different views:
$emailTemplate = 'The email body';
Here is my controller:
<?php
class Emails extends Controller{
//Send email to remamber the expirity date
public function sendReinder($data){
$emailTemplate = $this->view('emails/expirityRemainder');
$data=[
'recipient'=>'anEmail#yahoo.com',
'subject'=>'TheSubject',
'htmlBody'=>$emailTemplate,
'nonHtmlBody'=>'This is the body in plain text for non-HTML mail clients',
'sentMessage'=>'Message has been sent'
];
$email = new Email();
$email->sendMail($data);
}
}
The 'expirityRemainder.php' file contains a text:
Here will be the HTML code formatted
The PHPMailer file is inside of that libraries/PHPMailer folder.
The Email class send the email (on my server the below blank details are filled):
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
class Email{
public function sendMail($data){
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup SMTP servers smtp.topwebdeveloper.co.uk
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to 465 25 587
//Recipients
$mail->setFrom('', '');
//$mail->addAddress('', ''); // Add a recipient
//$mail->addAddress(''); // Name is optional
$mail->addAddress($data['recipient'], 'Nameee');
$mail->addReplyTo('', 'Information');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = $data['htmlBody'];
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
print_r($data);
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
print_r($data);
}
}
}
?>
This is the output:
Here will be the html code formatted
Message could not be sent.
Mailer Error: Message body emptyArray ( [recipient] => anEmail#yahoo.com [subject] => TheSubject [htmlBody] => [nonHtmlBody] => This is the body in plain text for non-HTML mail clients [sentMessage] => Message has been sent )`
I think the view content is expected to not be a string... The $data['htmlBody']inside if sendMail($data) did not receive the view content.
The view method works perfect for my MVC, except that situation when I try to load an mail text:
<?php
class Controller{
public function model($model){
require_once '../app/models/'.$model.'.php';
return new $model();
}
public function view($view, $data=[]){
if(file_exists('../app/views/'.$view.'.php')){
require_once '../app/views/'.$view.'.php';
} else {
die('vien not exists');
}
}
}
I created a new method but still not working:
<?php
public function loadEmailView($view, $data=[]){
if(file_exists('../app/views/'.$view.'.php')){
//ob_start();
//include('../app/views/'.$view.'.php');
//$file = ob_end_flush();
//echo file_get_contents('../app/views/'.$view.'.php');
//$data['htmlBody'] = require_once '../app/views/'.$view.'.php';
} else {
die('Email vien not exists');
}
}
None of the 3 above solutions not add the view content to my htmlBody variable:
<?php
class Emails extends Controller{
//Send email to remamber the expirity date
public function sendReinder($data){
$emailTemplate = $this->loadEmailView('emails/expirityRemainder');
//$emailTemplate = file_get_contents('email_template.php');
$data=[
'recipient'=>'anEmail#yahoo.com',
'subject'=>'TheSubject',
'htmlBody'=>$emailTemplate,
'nonHtmlBody'=>'This is the body in plain text for non-HTML mail clients',
'sentMessage'=>'Message has been sent'
];
$email = new Email();
$email->sendMail($data);
}
}
Thank you!
Related
I have a problem sending multiple email addresses functions. If I send a single email address, I can work. If I send multiple emails to the receiver, they cannot receive my message. I am using the PHPMailer function to do the email function with XAMPP. I am using the PHP array function to put the receiver's address in the array and use the while function to loop the receiver address to send it.
Below is my coding:
$address = array('st9overfindsolution#gmail','st7overfindsolution#gmail');
require 'class/class.phpmailer.php';
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
// $mail->SMTPDebug = 1;
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->Username = 'example#gmail.com';
$mail->Password = '1233aqqq';
$mail->SMTPSecure = 'ssl';
$mail->From = $_POST["email"];
$mail->FromName = $_POST["name"];
$mail->AddCC($_POST["email"], $_POST["name"]);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $_POST["subject"];
$mail->Body = $_POST["message"];
while(list ($key, $val) = each($address)){
$mail->AddAddress($val);
}
What I've tried?
1.I put all receiver email addresses in the array $address = array('st9overfindsolution#gmail','st7overfindsolution#gmail'); and use below while function code, but cannot work.
2.If send single email address without using while function, just can work, like below coding:
Hope someone can guide me on how to solve this problem. Thanks.
i have created new function named "sendmyemail" and inserted the code inside this function, so you can sent multiple emails by calling this function with email address.
<?php
/**
* This example shows sending a message using a local sendmail binary.
*/
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
function sendmyemail($whotoEmail){
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Set PHPMailer to use the sendmail transport
$mail->isSendmail();
//Set who the message is to be sent from
$mail->setFrom('from#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress($whotoEmail);
//Set the subject line
$mail->Subject = 'PHPMailer sendmail test';
//Read an HTML message body from an external file, convert referenced images to
embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), __DIR__);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message sent to '.$whotoEmail.'!';
}
}
sendmyemail('abcduser#gmail.com');
sendmyemail('efguser#gmail.com');
sendmyemail('hijkuser#gmail.com');
sendmyemail('lmnouser#gmail.com');
I'm using a MVC framework and i want to pass a view into PHPMailer body but I can't capture the view into a variable.
Controller handling view looks like this:
// Load View
public function view($view, $data = []){
// Check for view file
if(file_exists('../app/views/'.$view.'.php')){
require_once '../app/views/'.$view.'.php';
}else{
// View does not exist
die('View does not exist');
}
}
In controller i pass the view into the function sendMail but it first loads it than i get an error file_get_contents(): Filename cannot be empty:
$bodyMail = file_get_contents($this->view('booking/mailbody'));
sendEmail($bookingNumber, $id, $mailAddress, $bodyMail);
The helper function to handle PHPMailer function:
function sendEmail($bookingNumber, $id, $mailAddress, $bodyMail){
$mail = new PHPMailer(true);
//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "*********";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "**********";
$mail->Password = "********";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";
//Set TCP port to connect to
$mail->Port = 587;
$mail->From = "********";
$mail->FromName = "*******";
$mail->addAddress($mailAddress);
$mail->addAddress('*********');
$mail->isHTML(true);
$mail->Subject = "Reservation confirmed: ".$bookingNumber.$id."";
$mail->Body = $bodyMail;
$mail->AltBody = "This is plain text of mail";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
My question is there's a way to capture the view into a variable?
Would you approach this in a different way? If so, can you guys give me the right direction to take?
As per my comment, I suggest using output buffering to capture the output of your view
https://www.php.net/manual/en/function.ob-get-clean.php
And as #synchro suggest, review your usage of require_once()
// Load View, but capture it with output buffering
public function viewBuffered($view, $data = []){
// Check for view file
if(file_exists('../app/views/'.$view.'.php')){
ob_start();
require_once '../app/views/'.$view.'.php';
return ob_get_clean();
}else{
// View does not exist
die('View does not exist');
}
}
-or-
// Load View, but capture it with output buffering
public function viewBuffered($view, $data = []){
ob_start();
$this->view($view,$data);
return ob_get_clean();
}
I'm trying to include PHPmailer in functions.php
my code:
add_action('wp_ajax_nopriv_test_mailer', 'test_mailer');
function test_mailer () {
try {
require_once(get_template_directory('/includes/mail/PHPMailer.php'));
require_once(get_template_directory('/includes/mail/Exception.php'));
$mail = new PHPMailer(true); // Passing `true` enables exceptions
//Server settings
$mail->SMTPDebug = 4; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'test#gmail.com'; // SMTP username
$mail->Password = 'dummypassword!'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('test#gmail.com', 'Mailer Test');
$mail->addAddress('john.doe#gmail.com', 'John User'); // Add a recipient
$mail->addReplyTo('test#gmail.com');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject testing';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
wp_die();
}
I also tried to put require_once out of the try catch still the same error here is the snippet about the error
"PHP Fatal error: Uncaught Error: Class 'PHPMailer' not found"
I use betheme template and I stored the files PHPmailer in betheme/includes/mail.
As BA_Webimax pointed out, you should be using Wordpress' built-in email functions, though due to WP's reliance on outdated PHP versions, you will end up using a very old version of PHPMailer with it.
Back to your current problem: It's not your require_once statements that are failing, it's that you have not imported the namespaced PHPMailer classes into your namespace. Add these at the top of your script:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
Alternatively, use the FQCN when creating your instance:
$mail = new PHPMailer\PHPMailer\PHPMailer;
Note that this applies to the Exception class too, so you'd need to say:
catch (PHPMailer\PHPMailer\Exception $e) {
get_template_directory() returns the absolute path of the theme and doesn't take any params.
Try this for your includes:
require_once(get_template_directory().'/includes/mail/PHPMailer.php');
require_once(get_template_directory().'/includes/mail/Exception.php');
I want to send an email using PHPMailer and I'm using Codeigniter
public function check_email(){
$response = array('error' => false);
$email = $this->input->post('email');
$check_email = $this->fp_m->check_email($email);
if($check_email){
$this->load->library('phpmailer_library');
$mail = $this->phpmailer_library->load();
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress($email);
$mail->isHTML(true);
$mail->Subject = "Reset Password";
$mail->Body = "
Hi,<br><br>
In order to reset your password, please click on the link below:<br>
<a href='
http://example.com/resetPassword.php?email=$email
'>http://example.com/resetPassword.php?email=$email</a><br><br>
Kind Regards,<br>
Kokushime
";
if($mail->send()){
$response['error'] = false;
$response['message'] = "The Email Sent. Please Chect Your Inbox";
}else{
$response['error'] = true;
$response['message'] = "There's Something wrong while sending the message". $mail->ErrorInfo;
;
}
}else{
$response['error'] = true;
$response['message'] = 'The email that you entered is not associated with admin account';
}
echo json_encode($response);
}
But it gives me error Could not instantiate mail function.
BTW, I'm not using SMTP because i don't need that..
I hope that you can help me :)
You did not include your PHPMailer config. Since you are not using SMTP do you have this set?
$mail->isSendmail();
Also, assuming you are using CI3 it would probably be easier if you installed PHPMailer with composer and had it autoload.
I just tested this and it works fine using sendmail.
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class Phpmailer_test extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->isSendmail();
//Recipients
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
$mail->addReplyTo('info#example.com', 'Information');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
}
}
I haven't sent email using MVC before and am getting a bit stuck.
In my app folder, I have a libraries folder which has Controller.php, Core.php, Database.php and I created Email.php
In Email.php I have a class:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../vendor/autoload.php';
class Email {
public function sendMail()
{
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mail#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('mail#example.com');
$mail->addAddress('someone#example.com'); // Add a recipient // Name is optional
$mail->addReplyTo('mail#example.com');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
}
}
I am now trying to trigger the sending of the email when I access the email view. However, I don't know what to put in the controller. The code below gives me an error.
public function email()
{
$this->sendMail();
$this->view('pages/email');
}
Fatal error: Uncaught Error: Call to undefined method Pages::sendMail()
You have to create an instance of the class Email:
$email = new Email();
$email->sendMail();