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;
}
}
}
Related
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!
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();
I'am newbie in php. I'am trying to send email using php but I don't know what's wrong in my code. I googled a lot but nothing has worked yet. Here is my php code. I'am using class.phpmailer.php.
<?php
require("phpmailer-master/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
IsSMTP(); // send via SMTP
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "myemail#googlemail.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
$webmaster_email = "recipient#googlemail.com"; //Reply to this email ID
$email="username#domain.com"; // Recipients email ID
$name="myname"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "Webmaster";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"Webmaster");
$mail->WordWrap = 50; // set word wrap
$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment
$mail->IsHTML(true); // send as HTML
$mail->Subject = "This is the subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
I could finally send a mail using php. Here is the code:
<?php
require_once('class.phpmailer.php');
include("class.smtp.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet="UTF-8";
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = 'sender#mail.com';
$mail->Password = 'sender_password';
$mail->SMTPAuth = true;
$mail->From = 'sender#mail.com';
$mail->FromName = 'sender';
$mail->AddAddress("sender#mail.com");
$mail->AddReplyTo("sender#mail.com", 'Information');
$mail->IsHTML(true);
$mail->Subject = "Sample exmple to check proper working of mail function";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->Body = "Hello ";
$path = $_POST['upload'];
$mail->AddAttachment($path); // attachment
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message sent!";
}
?>
<?php
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
// Comment out this line here it is wrong
// IsSMTP(); // send via SMTP
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "username#gmail.com"; // SMTP username
$mail->Password = "password"; // SMTP password
$webmaster_email = "username#doamin.com"; //Reply to this email ID
$email = "username#domain.com"; // Recipients email ID
$name = "name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "Webmaster";
$mail->AddAddress($email, $name);
$mail->AddReplyTo($webmaster_email, "Webmaster");
$mail->WordWrap = 50; // set word wrap
// i would also comment out these lines, get it working without attachments first
// then add then back in after (if you want attachments)
// $mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
// $mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment
$mail->IsHTML(true); // send as HTML
$mail->Subject = "This is the subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if (!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
// at the end of the pasted code above, you have these lines (below here) doubled up.
// remove them
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
I'm trying to send a file as an email attachment, but for some reason if the file is > 100k then the email doesn't go through, even though I get the email sent message.
It may also be a limit on the attachments in IIS smtp setting, but when I unchecked the Limit session size and limit message size options, it didn't change anything. I may have to restart the server tonight...
I don't know if it's a php.ini setting, or what.
<?
$path_of_attached_file = "Images/marsbow_pacholka_big.jpg";
require 'include/PHPMailer_5.2.1/class.phpmailer.php';
try {
$mail = new PHPMailer(true); //New instance, with exceptions enabled
$body = $message; //"<p><b>Test</b> another test 3.</p>";
$mail->AddReplyTo("admin#example.com","Admin");
$mail->From = "admin#example.com";
$mail->FromName = "Admin";
$mail->AddAddress($to);
$mail->Subject = "First PHPMailer Message";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->WordWrap = 80; // set word wrap
$mail->MsgHTML($body);
$mail->IsHTML(true); // send as HTML
if($attach){
$mail->AddAttachment($path_of_attached_file);
}
$mail->Send();
echo 'Message has been sent.';
} catch (phpmailerException $e) {
echo $e->errorMessage();
}
?>
I might be wrong because I don't use IIS but the code you provided would actually use a native MTA not SMTP. As far as I know you have to use the IsSMTP() method to let PHPMailer know that you intend to use SMTP.
Something like this:
<?
$path_of_attached_file = "Images/marsbow_pacholka_big.jpg";
require 'include/PHPMailer_5.2.1/class.phpmailer.php';
try {
$mail = new PHPMailer(true); //New instance, with exceptions enabled
$body = $message; //"<p><b>Test</b> another test 3.</p>";
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.yourdomain.com"; // sets the SMTP server
$mail->Port = 25; // set the SMTP port
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
$mail->AddReplyTo("admin#example.com","Admin");
$mail->From = "admin#example.com";
$mail->FromName = "Admin";
$mail->AddAddress($to);
$mail->Subject = "First PHPMailer Message";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->WordWrap = 80; // set word wrap
$mail->MsgHTML($body);
$mail->IsHTML(true); // send as HTML
if($attach){
$mail->AddAttachment($path_of_attached_file);
}
$mail->Send();
echo 'Message has been sent.';
} catch (phpmailerException $e) {
echo $e->errorMessage();
}
?>
Your code is not actually checking if the message was sent or not.
You need to change your code to check the return of the send method
if ($mail->Send())
echo 'Message has been sent.';
else
echo 'Sorry there was an error '.$mail->ErrorInfo;
This should give you the error message saying what is up if it does go wrong.
I'm trying to send an e-mail to multiple e-mail address in my database. Here is my current code.I need to have them query my database and send the e-mail to each e-mail address.It is working but email was send to the first e-mail address only, and got an error "Fatal error: Call to undefined method stdClass::AddAddress()".Where am I going wrong here?
<?php
$elist = $database->getRows("SELECT * FROM `emails`");
foreach($elist as $emails){
$frm = 'test#gmail.com';
$sub = 'Weekly Work Report';
ob_start();
include_once('mail_content.php');
$mail_body = ob_get_contents();
ob_end_clean();
$to = $emails['email'];
$mailstatus = lm_mail('1', '2', $to, '3', $frm, 'HR', $sub, $mail_body);
if ($mailstatus == 'ok') {
$response->redirect('index.php?com_route=user_report');
} else {
echo $mailstatus;
}
}
?>
function lm_mail($head_mid='',$head_mname='',$to_mid ,$to_mname='',$reply_mid,$reply_mname='',$subject,$body,$attachments='')
{
include_once 'phpmailer/mail_config.php';
if(SMTP_mail)
{
// Send SMTP Mails
$mail->From =$head_mid ; // From Mail id
$mail->FromName = $head_mname; // From Name
$mail->AddAddress($to_mid,$to_mname); // To Address
$mail->AddReplyTo($reply_mid,$reply_mname); // From Address
$mail->Subject=$subject;
$mail->Body = $mail_body.$body; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
return $mail->ErrorInfo;
}
else
{
return 'ok';
}
}
else
{
$mail = new PHPMailer(); // defaults to using php "mail()"
$mail->AddReplyTo($reply_mid,$reply_mname); // Sender address
$mail->AddReplyTo($reply_mid,$reply_mname); // replay to address
$address = $to_mid; // to addtesas
$mail->AddAddress($address, $to_mname);
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($mail_body.$body);
if(!$mail->Send())
{
return $mail->ErrorInfo;
}
else { return 'ok'; }
}
}
In the first conditional of the lm_mail function call there is no object being instantiated.
if(SMTP_mail)
{
// No $mail object?
// Send SMTP Mails
$mail->From =$head_mid ; // From Mail id
Try adding:
if(SMTP_mail)
{
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
// Have to manually set language if PHPMailer can't determine
$mail->SetLanguage("en", 'includes/phpMailer/language/');
I'm guessing you are using SMTP, because I don't see where $mail comes from.
Since one email is sending, my guess is that phpmailer/mail_config.php sets up a $mail object and sets the SMTP_mail constant, and then it goes out of scope after the first function call and the file is only included once so it doesn't get defined again.
After that it wasn't defined as a PHPMailer object, so it is cast as a stdClass when you do the object assignment $mail->From = $head_mid.
Try taking the code out of mail_config.php and replicating it in your send function, or add a function to mail_config.php that provides a factory to getting a PHPMailer object that is configured for your needs.