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 :) .
Related
When I try to send the form on my web site, I got this error:
Sorry ..., it seems that my mail server is not responding. Please try again later!
I thing that is a problem with me contact_me.php file
There is the code
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
error_reporting(E_STRICT);
date_default_timezone_set('Portugal/Lisbon');
require_once('class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "a.a.pt"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "a.a.pt"; // sets the SMTP server
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "a#a.pt"; // SMTP account username
$mail->Password = "a"; // SMTP account password
$mail->SetFrom('a#a.pt', 'First Last');
$mail->AddReplyTo("a#a.pt","First Last");
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$address = "a#a.pt";
$mail->AddAddress($address, "a#a.pt");
$formcontent=" From: $name \n Phone: $phone \n Email: $email \n Message: $message";
$formcontent= eregi_replace("[\]",'',$formcontent);
$mail->MsgHTML($formcontent);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
You can try using my class, i'm sure this runs 100%, even if it does not work for you is a credential problem or email server that for some reason waste for the connection
class Mailplus{
protected $host = "ssl://smtps.*.com";
protected $port = "123";
protected $username = "email#example";
protected $password = "*";
protected $from = "Email from - Name <email#example>";
protected $smtp;
function __construct() {
require_once "Mail.php";
$this->smtp = Mail::factory('smtp',
array ('host' => $this->host,
'port' => $this->port,
'auth' => true,
'username' => $this->username,
'password' => $this->password));
}
function SendMail($to ,$subject,$body){
$headers = array ('From' => $this->from,
'Subject' => $subject,
'MIME-Version' =>'1.0',
'Content-Type' =>'text/html',
'charset' => 'ISO-8859-1');
$mail = $this->smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
return "Ex_001";
} else {
return true;
}
}
}
Then use this comand
$mail = new Mailplus ();
if ($mail.SendMail("to#example.com","Subject","html emial")==ture){
//email sent
else{
//email not sent
}
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');
<?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.
code:
class email extends main{
function email($to, $to_name, $subject, $message, $type, $schoolTitle, $schoolEmail, $attachments){
$this->to = $to;
$this->to_name = $to_name;
$this->subject = $subject;
$this->message = $message;
$this->type = $type;
$this->schoolTitle = $schoolTitle;
$this->schoolEmail = $schoolEmail;
$this->attachments = $attachments;
}
function connect(){
require_once PLUGINS.'PHPMailer-20160322/PHPMailerAutoload.php';
$this->mail = new PHPMailer;
$this->mail->isSMTP();
$this->mail->SMTPDebug = 0;
$this->mail->Debugoutput = 'html';
$this->mail->Host = "**********";
$this->mail->Port = **;
$this->mail->SMTPAuth = true;
$this->mail->SMTPSecure = 'tls';
//$mail->Sender="************";
$this->mail->Username = "**************";
$this->mail->Password = "**************";
}
function sendSingle(){
//this is used in the bulk emailer when the connect it called so we can send multiple emails from 1 connection
$this->mail->addAddress($this->to, $this->to_name);
$this->mail->Subject = $this->subject;
$this->mail->msgHTML($this->getMessage());
$this->mail->AltBody = strip_tags($this->message);
$this->mail->setFrom($this->schoolEmail, $this->schoolTitle);
$this->mail->AddReplyTo($this->schoolEmail, $this->schoolTitle);
foreach($this->attachments as $item){
$this->mail->addAttachment($item);
}
if (!$this->mail->send()) {
return false;
} else {
return true;
}
}
}
Result I want:
I want to be able to use the testEmail and testTitle
$this->schoolEmail= "chris.beckett#testing.co.uk";
$this->schoolTitle= "Chris Beckett";
$this->mail->setFrom($this->schoolEmail, $this->schoolTitle);
$this->mail->AddReplyTo($this->schoolEmail, $this->schoolTitle);
What I've tried and worked:
I don't understand why the testTitle works but when I try and pass in the testEmail the email doesn't send or it will send but it won't have the parameters of from: or reply to:
$this->schoolEmail= "chris.beckett#testing.co.uk";
$this->schoolTitle= "Chris Beckett";
$this->mail->setFrom('name#yourdomain.com', $this->schoolTitle);
$this->mail->AddReplyTo('name#yourdomain.com', $this->schoolTitle);
Debug Info showed that it worked but the email not showing up in my inbox:
CLIENT -> SERVER: From: Chris Beckett <chris.beckett#testing.co.uk>
CLIENT -> SERVER: Reply-To: Chris Beckett <chris.beckett#testing.co.uk>
Could anyone explain what I could be doing wrong?
I'm using PHPmailer to send emails and I've created a function that prepares the email and sends it. If I try to use this function more than once in a script it stops the script execution when it trys to send a second email using the same function.
my function:
public static function sendEmail($from, $fromName, $to, $subject, $body){
require("includes/class.phpmailer.php");
$mailer = new PHPMailer();
$mailer->IsSMTP(true);
$mailer->Host = 'ssl://smtp.gmail.com:465';
$mailer->SMTPAuth = true;
$mailer->Username = 'removed';
$mailer->Password = 'removed';
$mailer->From = $from;
$mailer->FromName = $fromName;
$mailer->AddAddress($to);
$mailer->Subject = $subject;
$mailer->Body = $body;
$mailer->WordWrap = 100;
if ($mailer->Send()) {
return true;
} else {
return false;
}
}
Why is this happening? Is it anything to do with creating a new phpmailer object each time?
I think you should use require_once() instead of require