PHPMailer - sending email with a function - php

I need to send emails when users do particular things like fill in a form, submit a request etc. These happen on different pages.
I know the default use of PHPMailer is as below:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('from#example.com', 'Your Name');
$mail->addAddress('myfriend#example.net', 'My Friend');
$mail->Subject = 'First PHPMailer Message';
$mail->Body = 'Hi! This is my first e-mail sent through PHPMailer.';
if(!$mail->send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
Is it possible to use the mail() class without having to re-specify the username, password and message to the mail function each time??
Essentially could you have a fuction like:
sendMail($from, $to, $subject, $body);
Which then passes the variables given to an instance of PHPMailer?
Similar to this question.

require 'vendor/autoload.php';
class MyMail extends PHPMailer
{
private $_host = 'your stmp server name';
private $_user = 'your smtp username';
private $_password = 'your password';
public function __construct($exceptions=true)
{
$this->Host = $this->_host;
$this->Username = $this->_user;
$this->Password = $this->_password;
$this->Port = 465;
$this->SMTPAuth = true;
$this->SMTPSecure = 'ssl';
$this->isSMTP();
parent::__construct($exceptions);
}
public function sendMail($from, $to, $subject, $body)
{
$this->setFrom($from);
$this->addAddress($to);
$this->Subject = $subject;
$this->Body = $body;
return $this->send();
}
}
$m = new MyMail();
$result = $m->sendMail('test#test.hu', 'youremail#yourdomain.com', 'Test from script', 'test message from script');

Related

How to use PHPMailer (localhost+gmail) in a custom MVC framework

I'm trying to send emails using the PHPMailer library and gmail in my MVC project. Here's what I did in my project. My project and files:
myproject
-app
-controllers
-AccountController.php
-core
-PHPMailer
-PHPMailer.php
-SMTP.php
-Exception.php
-MyCustomMailer.php
My AccountController.php has following code:
namespace App\Controllers;
use Core\PHPMailer\MyCustomMailer;
...
class AccountController extends Controller {
...
public function sendSecurityCode(){
$user_email = "example#gmail.com";
$name = "John Doe";
$code = "ranD0m"
$mailer = new MyCustomMailer(true);
$send = $mailer->sendSecurityCodeEmail($user_email, $name, $code);
if($send) die("Sent.");
else die("Not sent.");
}
}
And MyCustomMailer.php is somthing like this:
namespace Core\PHPMailer;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once('PHPMailer.php');
require_once('SMTP.php');
class MyCustomMailer extends PHPMailer
{
private $_host = 'smtp.gmail.com';
private $_user = ''userJohnDoe#gmail.com';';
private $_password = 'paSsW0rd';
public function __construct($exceptions=true)
{
$this->isSMTP();
$this->SMTPDebug = 1;
$this->Host = $this->_host;
$this->Port = 587;
$this->Username = $this->_user;
$this->Password = $this->_password;
$this->SMTPAuth = true;
$this->SMTPSecure = 'tls';
parent::__construct($exceptions);
}
// send security code email
public function sendSecurityCodeEmail( $email, $name, $code){
$mail_subject = "Security code account";
$html_body = "";
$mail_body = " Hey here is a test email and security code is: ". $code;
$email_sent = self::sendEmail($email, $name, $mail_subject, $html_body, $mail_body);
return $email_sent;
}
public static function sendEmail($to_email, $to_name, $subject, $html_body, $email_body){
$mail_sent = false;
try{
$mail = new PHPMailer;
$mail->setFrom("noreply#example.com", "Example");
$mail->addAddress($to_email,$to_name);
$mail->Subject = $subject;
if(!empty($html_body)) {
$mail->isHTML(true);
$mail->AltBody = $email_body;
$mail->Body = $html_body;
} else{
$mail->Body = $email_body;
}
if($mail->send()) $mail_sent = true;
}
catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
return $mail_sent;
}
}
Getting errors Uncaught Error: Class 'PHPMailer\PHPMailer\Exception' not found. What is right way to implement it in my MVC project??
Incase someone having similar issues or looking for a MVC implementation: I made it work by adding the missing Exception.php in MyCustomMailer.php. Now it looks like this :
...
require_once(__DIR__.'/PHPMailer.php');
require_once(__DIR__.'/SMTP.php');
require_once(__DIR__.'/Exception.php');
...
It solved the PHPMailer\PHPMailer\Exception' not found problem. Then got another error Could not connect to SMTP host and solved it by updating the sendEmail function in MyCustomMailer.php. Here is the new sendEmail function:
public static function sendEmail($to_email, $to_name, $subject, $html_body, $email_body){
$mail_sent = false;
try{
$mail = new PHPMailer;
$mail->setFrom("noreply#example.com", "Example");
$mail->addAddress($to_email,$to_name);
$mail->Subject = $subject;
if(!empty($html_body)) {
$mail->isHTML(true);
$mail->AltBody = $email_body;
$mail->Body = $html_body;
} else{
$mail->Body = $email_body;
}
// added Gmail hack
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
if($mail->send()) $mail_sent = true;
}
catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
return $mail_sent;
}
set the smtp username and password correctly and It's working just fine :) .

Could not instantiate mail function - Codeigniter and PHPMailer

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

PHPMAILER Sending Email in attached file

<?php
include('phpmailer.php');
class Mail extends PhpMailer
{
// Set default variables for all new objects
public $From = 'noreply#domain.com';
public $FromName = SITETITLE;
public $Host = 'smtp.gmail.com';
public $Mailer = 'isSMTP';
public $SMTPAuth = true;
public $Username = 'email#gmail.com';
public $Password = 'password';
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();
}
}
I am Using this Code for Email.php file and it works but it sends Mail in Attachment Not in Normal Form...
Email Attachment Showing in Email
Email Attachment Output
Here is link where i am using it for verification purposes.
http://monthlyreport.ultimatefreehost.in
At index.php I am using Like this
//send email
$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 Mail();
$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;
Your functions should return the values.
Use return $this->Body = $body; at the end of body(), and similarly do it for the other functions as well.

PHPMailer sends duplicate email

PHPMailer
<?php
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->IsHTML(true);
$mail->SMTPSecure = "tls";
$mail->Mailer = "smtp";
$mail->Host = "smtp.office365.com";
$mail->Port = 587;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "xxx";
$mail->Password = "xxx";
$mail->setFrom('xxx', 'Website');
//Send to Admin
$AdminEmail = 'admin.example#gmail.com';
$mail->AddAddress($AdminEmail, $AdminName);
$mail->Subject = "This is an email";
$mail2 = clone $mail;
$body = 'Hi Admin. This is an email';
$mail->Body = $body;
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
//Send to User
$UserEmail = 'user.example#gmail.com';
$mail2->AddAddress($UserEmail, $UserName);
$body2 = 'Hi User. This is an email';
$mail2->Body = $body2;
if(!$mail2->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail2->ErrorInfo;
} else {
echo 'Message has been sent.';
}
?>
I have an issue where when i send the emails, Admin will receive $mail and $mail2 when they supposed to just receive $mail. While there's no problem with User. Works fine by receiving $mail2. I've tried to put $mail->ClearAddresses(); but it's still the same. By chance, what is the problem?
Clone the email variable before adding the address and stuff of the admin. (As suggested in the comments)
You need to create different-different object for both admin and user email
//Send to Admin
$mail = new PHPMailer;
$mail->IsHTML(true);
$AdminEmail = 'admin.example#gmail.com';
$mail->AddAddress($AdminEmail, $AdminName);
$mail->Subject = "This is an email";
$mail2 = clone $mail;
$body = 'Hi Admin. This is an email';
$mail->Body = $body;
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
//Send to User
$mail = new PHPMailer;
$mail->IsHTML(true);
$UserEmail = 'user.example#gmail.com';
$mail->AddAddress($UserEmail, $UserName);
$body2 = 'Hi User. This is an email';
$mail->Body = $body2;
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}

PHPMailer Problems

Okay, so I've downloaded PHP Mailer's class, required it using require_once then make a function for sending mail:
public function sendMail($to, $subject, $body) {
$mail = new phpmailer;
$mail->IsSMTP(); // set mailer to use SMTP
$mail->SMTPAuth = true;
$mail->Username = 'USERNAME';
$mail->Password = 'PASSWORD';
$mail->Port = 465;
$mail->SMTPSecure = 'SSL';
$mail->From = "EMAIL";
$mail->FromName = "FROM NAME";
$mail->Host = "smtp.gmail.com;"; // specify main and backup server
if(is_array($to)) {
foreach($to as $x) {
$mail->AddAddress($x);
}
} else {
$mail->AddAddress($to);
}
$mail->AddReplyTo("REPLY EMAIL", "REPLY NAME");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = $subject;
$mail->Body = $body;
if(!$mail->Send()){
return false;
}
}
And when I go to do (it's in the class $core)
if($core->sendMail('MYEMAIL#gmail.com', 'Something', 'Some body')) {
echo 'Mail sent';
} else {
echo 'Fail';
}
It returns fail. The code in the script holds the correct information, I've just used placeholders for posting it here.
$mail contains the error message, do the following:
if (!$mail->Send()) {
throw new Exception($mail->ErrorInfo);
}
instead of just returning "false".
if(!$mail->Send()){
return false;
}
should be
if(!$mail->Send()){
return false;
} else {
return true;
}
because functions by default return false, when the return value is not specified inside the function.
You can also go with the cleaner version:
return $mail->Send();

Categories