PHPmailer failing if trying to send two emails in same script - php

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

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 :) .

PHPMailer not working when trying to create using a PHP Function

I am using PHPMailer for sending emails. But I have to write that long code of sending emails on every page. So I thought of trying to put the whole stuff into a function and just calling it whenever I want to make the things dry, simple and easier. But its not working when trying to send emails. I tried the following:
functions.php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
$settings = $pdo->prepare("SELECT * FROM settings");
$settings-> execute();
$set = $settings->fetch();
function newMail($name, $email, $sub, $msg, $set) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = $set['set_smtp_host'];
$mail->Port = $set['set_smtp_port'];
$mail->SMTPSecure = $set['set_smtp_security'];
$mail->IsHTML(true);
$mail->SMTPAuth = true;
$mail->Username = $set['set_smtp_uname'];
$mail->Password = $set['set_smtp_pass'];
$mail->setFrom($set['set_noreply_email'], $set['set_site_name']);
$mail->addAddress($email, $name);
$mail->Subject = $sub;
$mail->Body = $msg;
$mail->Send();
}
Now I tried calling the function on another page (where functions.php is included) this way:
$fname = (!empty($_POST['fname']))?$_POST['fname']:null;
$email = (!empty($_POST['email']))?$_POST['email']:null;
$sub = ''.$title.' - Account Verification Link';
$msg = 'SOME BODY MESSAGE';
if(newMail($fname, $email, $sub, $msg)){
echo alert_success("Registration successful! Please check your email and click on the activation link to activate your account. If you did not receive any email within 5 minutes then <a href='resend.php'>click here</a> to resend it.");
}else{
echo alert_success("Registration successful! But unfortunately, we could not send you a verification email. Please <a href='resend.php'>click here</a> to resend it.");
}
Here its always returning the else message. Am I wrong coding something here?
Modify your function newMail at the end by :
return $mail->Send();
The send method return true in case the mail is sent , so you function should return this value , if not :
if(newMail(...)){ }
Will always be false that why the else case is applied.
function newMail($name, $email, $sub, $msg, $set) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = $set['set_smtp_host'];
$mail->Port = $set['set_smtp_port'];
$mail->SMTPSecure = $set['set_smtp_security'];
$mail->IsHTML(true);
$mail->SMTPAuth = true;
$mail->Username = $set['set_smtp_uname'];
$mail->Password = $set['set_smtp_pass'];
$mail->setFrom($set['set_noreply_email'], $set['set_site_name']);
$mail->addAddress($email, $name);
$mail->Subject = $sub;
$mail->Body = $msg;
return $mail->Send(); // add return here
}

How to fix send different emails to different people PHPMailer

I am going to send different emails to different people.
First email sent normal but second one is waiting for 180 sec and then start to send. I couldn't find any default settings. Once sent an email others are going to POOLING and failed it.
I have different bodies and different subjects.
code 1:
sendEmail(false, $email, $message, $subject, $dep_type);
sendEmail(true, $email, $message_client, $subject_client);
sendEmail function :
function sendEmail($client, $email, $message, $subject, $dep_type = null)
{
$from_mail = 'hello#example.com';
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->Host = 'email-smtp.us-east-1.amazonaws.com';
$mail->SMTPAuth = true;
$mail->Username = 'username';
$mail->Password = 'password';
$mail->From = $from_mail;
$mail->FromName = "SenderName";
if ($client) {
$mail->addAddress($email);
} else {
$mail->addAddress('welcome#example.com');
}
$mail->addReplyTo($from_mail, 'name');
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->send();
}
https://aws.amazon.com/de/premiumsupport/knowledge-center/ec2-port-25-throttle/
Amazon EC2 throttles traffic on port 25 of all EC2 instances by
default, but you can request for this throttle to be removed.

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.

Sending email using smtp gmail in phpmailer

I tried sending email using smtp gmail using phpmailer. My gmail account got suspended saying that there is an unusual activity. Here is the code I have used for sending emails. What's the correct way of sending emails using smtp gmail in phpmailer?
My question is not duplicate. I have already tried this : Send email using the GMail SMTP server from a PHP page
I'm using phpmailer, and my accounts getting suspended.
<?php
include('phpmailer.php');
class Mail extends PhpMailer
{
// Set default variables for all new objects
public $From = 'noreply#exmaple.org';
public $FromName = SITETITLE;
public $Host = 'smtp.gmail.com';
public $Mailer = 'smtp';
public $SMTPAuth = true;
public $Username = 'username#gmail.com';
public $Password = 'password';
public $SMTPSecure = 'tls';
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();
}
}
Here is my php code :
$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('noreply#example.org');
$mail->addAddress($to);
$mail->subject($subject);
$mail->body($body);
$mail->send();
//redirect to index page
header('Location: index.php?action=joined');
exit;

Categories