PHPMailer not working when function is within and included file - phpmailer

Something is mighty odd. I created a basic test file with the code from PHPMailer.
# Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'includes/PHPMailer/PHPMailer.php';
require 'includes/PHPMailer/SMTP.php';
require 'includes/PHPMailer/Exception.php';
function sendCampaignEmail ($email, $firstname, $lastname)
{
$mail = new PHPMailer(true); // Create a new PHPMailer instance. Passing `true` enables exceptions.
try {
//Server settings
# $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output. SMTP::DEBUG_SERVER = client and server messages
# $mail->SMTPDebug = SMTP::DEBUG_CLIENT; // SMTP::DEBUG_CLIENT = client messages
$mail->SMTPDebug = SMTP::DEBUG_OFF; // SMTP::DEBUG_OFF = off (for production use)
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'myhostxxxx.co.uk'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'oobaclub#xxxxxxxxx.co.uk'; // SMTP username
$mail->Password = 'xxxxxmyEmailPasswordxxxxx'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 465; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('myfromemail.co.uk', 'My Name');
$mail->addAddress($email, $firstname . ' ' . $lastname); // Add a recipient
$mail->addReplyTo('myfromemail.co.uk', 'My Name');
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'Dear ' . $firstname . ' ' . $lastname . '<br/><br/>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 '<br/>Message has been sent to ' . $email . ' (' . $firstname . ' ' . $lastname . ')';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
$names= array();
$id=0;
$names[$id]['email'] = "atestemail#gmail.com";
$names[$id]['first_name'] = "Bob";
$names[$id]['last_name'] = "gMail"; $id++;
$names[$id]['email'] = "anothertest#testingmyemail.co.uk";
$names[$id]['first_name'] = "Sid";
$names[$id]['last_name'] = "Smith"; $id++;
$count=0;
while ($count < count($names))
{
sendCampaignEmail ($names[$count]['email'], $names[$count]['first_name'], $names[$count]['last_name']);
$count++;
}
THIS CODE ABOVE WORKS FINE.
So... Then, I took the function and put it into an Included file (where all my functions are: "globalfunctions.php").... And now it says "Fatal error: Uncaught Error: Class 'PHPMailer' not found"
So, now, at the top of my index.php, I have:
## PHP MAILER - # Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once 'includes/PHPMailer/PHPMailer.php';
require_once 'includes/PHPMailer/SMTP.php';
require_once 'includes/PHPMailer/Exception.php';
require_once 'includes/connect.php';
require_once 'includes/globalfunctions.php';
I am confused as everything else works. All my other functions work. I thought namespaces were global... But, I tried adding the "use" code into the function... but, as expected, that didn't work either....
I am stumped.

PHP use declarations are local aliases that apply only to the file they appear in. You have to add a use statement in every file that uses that class; you can't put all your declares in one file and then include it from somewhere else.
Now might be a good time to learn how to use composer as it takes care of a lot of this.

Related

DKIM not verified but dns record match key

Strugglign to get DKIM working. currently this is mail-tster result.
https://www.mail-tester.com/test-38w40jo78
im mainly missing the DKIM here is my dns records.
truebud.ca text = "truebud-64839v5873958h3ddrg._domainkey.truebud.ca k=rsa\; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChKyCHHZEkrYfTdcB2VX0nKL8Vhicb+xQsNswOgo5+IK2ipg97VJb+lKAT+jHMXyk4KPTkUUI/8rwa2IfUKsr/BQXy6csNkmM0Y00H5/+QRAYn+ktoRWO1zXvO2sygzCELgGxcj5pHkOd4xLGhTnTpHh7UAjTp" "/swV5E18dpAubQIDAQAB"
truebud.ca text = "v=DMARC1\; p=none"
truebud.ca text = "v=spf1 a mx ip4:216.221.70.222 ~all"
truebud.ca text = "_domainkey.truebud.ca o=~\; r=info#truebud.ca"
and here is my code for phpmailer
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// 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 'vendor/phpmailer/src/Exception.php';
require 'vendor/phpmailer/src/PHPMailer.php';
require 'vendor/phpmailer/src/SMTP.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
$site = 'truebud.ca';
$sitename = 'Truebud';
try {
//Server settings
//$mail->isSMTP(); // Send using SMTP
$mail->Host = '216.221.70.222'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info#'.$site; // SMTP username
$mail->Password = '[pass]'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('info#'.$site,$sitename);
$mail->addAddress('test-38w40jo78#srv1.mail-tester.com');
$mail->addReplyTo('info#'.$site,$sitename);
$mail->addCC('cc#'.$site);
$mail->addBCC('bcc#'.$site);
// Attachments
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Truebud promotion';
$mail->Body = 'wall o' text';
$mail->AltBody = 'wall 'o text';
$mail->AddCustomHeader("List-Unsubscribe: <mailto:unsubscribe#".$site."?subject=Unsubscribe>,<http://".$site."/unsubscribe.php>");
$mail->DKIM_domain = $site;
$mail->DKIM_private = "rsa.private"; //path to file on the disk.
$mail->DKIM_selector = $sitename."-64839v5873958h3ddrg";// change this to whatever you set during step 2
$mail->DKIM_passphrase = "";
$mail->DKIM_identity = $mail->From;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Ive been at this for a week. What am i missing?
Their error says:
We were not able to retrieve your public key.
Please ensure that you inserted your DKIM TXT DNS record on your domain truebud.ca using the selector Truebud-64839v5873958h3ddrg.
I can see what's wrong — your DKIM DNS entry is incorrectly formatted.
# dig txt Truebud-64839v5873958h3ddrg._domainkey.truebud.ca
Truebud-64839v5873958h3ddrg._domainkey.truebud.ca. 120 IN TXT "truebud-64839v5873958h3ddrg._domainkey.truebud.ca v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChKyCHHZEkrYfTdcB2VX0nKL8Vhicb+xQsNswOgo5+IK2ipg97VJb+lKAT+jHMXyk4KPTkUUI/8rwa2IfUKsr/BQXy6csNkmM0Y00H5/+QRAYn+ktoRWO1zXvO2sygzCELgGxcj5pHkOd4xLGhTnT" "pHh7UAjTp/swV5E18dpAubQIDAQAB"
You've got the hostname inside the record value - it should start with v=DKIM1, like:
truebud.ca text = "v=DKIM1; k=rsa\; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChKyCHHZEkrYfTdcB2VX0nKL8Vhicb+xQsNswOgo5+IK2ipg97VJb+lKAT+jHMXyk4KPTkUUI/8rwa2IfUKsr/BQXy6csNkmM0Y00H5/+QRAYn+ktoRWO1zXvO2sygzCELgGxcj5pHkOd4xLGhTnTpHh7UAjTp" "/swV5E18dpAubQIDAQAB"
However, while I was testing that I saw you had changed it, so I guess you spotted the same mistake!

problems with server SMTP PHPMailer

I have a problem with phpmailer, I have the correct SMPT server data and also the username and password, but it still marks me an error in the credentials, this is my code
<?php
include ("class.phpmailer.php");
include ("../vendor/phpmailer/phpmailer/PHPMailer.php");
include ("../vendor/phpmailer/phpmailer/src/SMTP");
// 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 '../vendor/phpmailer/phpmailer/src/Exception.php';
require '../vendor/phpmailer/phpmailer/src/PHPMailer.php';
require '../vendor/phpmailer/phpmailer/src/SMTP.php';
require '../vendor/autoload.php';
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Load Composer's autoloader
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'admin#ucarolina.mx'; // SMTP username
$mail->Password = '******'; // SMTP password
$mail->SMTPSecure = 'TSL'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('luribe#qvoz.com');
$mail->addAddress($email, $name); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $contact_message;
$mail->AltBody = $contact_message;
$mail->send();
echo "Mensaje enviado";
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>
and this is the error that marks me
SMTP Error: Could not authenticate.
Message could not be sent. Mailer Error: SMTP Error: Could not authenticate.
There is a line where SMTPSecure has to be specified. You have that line, but tls has been mistyped as TSL. Let's change that:
Change
$mail->SMTPSecure = 'TSL';
to
$mail->SMTPSecure = 'tls';
Additionally, you should add an if/then surrounding $mail->send(); like so:
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
If the mail is not sent, your if statement will catch that and report the error. See an example of such error handling in PHPMailer example: https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps

AddStringAttachment giving unusual results

I am sending attachments (CSV) which I have been sending for years using mail() but decided to migrate to SMTP for better reliability.
Code 1 (CSV attachment)
$attachment = $this->CSVData; // "Date","Name","Dept" ... \n"2019-03-13","Dave" ...
$encoding = 'base64';
$contentType = 'text/csv';
$filename = $this->createFileName(); //Get FileDate and Name
$recipient = $delivery_email; // xxxxxxx#gmail.com
$subject = $this->emailHeader['subject'] . " CSV Data";
$message = 'Daily Data File';
$mail = new PHPMailer\PHPMailer\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 = SMTP_HOST; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = SMTP_USER; // SMTP username
$mail->Password = SMTP_PASS; // SMTP password
$mail->SMTPSecure = SMTP_AUTH; // Enable TLS encryption, `ssl` also accepted
$mail->Port = SMTP_PORT; // TCP port to connect to
//Recipients
$mail->setFrom($this->fromEmail, $this->fromEmailName); // Add a FROM
$addresses = explode(',', $recipient);
foreach ($addresses as $address) {
$mail->AddAddress(trim($address)); // Add a recipient(s)
}
if ( !empty($this->emailCC) ) $mail->addCC($this->emailCC); // Add a CC
//13-03-2019: Add the attachment to the email
$mail->AddStringAttachment($attachment, $filename, $encoding, $contentType);
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'This email is formatted in HTML';
$mail->send();
$this->fo->printStatus('Email successfully sent to: '. $recipient );
return true;
} catch (Exception $e) {
$this->fo->printStatus( basename(__FILE__) .' '. __LINE__ . ': Message could not be sent. Mailer Error: '. $mail->ErrorInfo );
return false;
}
The email gets delivered to me BUT ...
Problems:
When viewing in Gmail browser - I get message: "
Gmail virus scanners are temporarily unavailable – The attached files haven't been scanned for viruses. Download these files at your own risk."
When viewing in Gmail browser - I cant save/download the file? (clicking the download button does nothing)
When clicking attachment to view in browser, I now get error: "Whoops. There was a problem while previewing this document"
I try "Show Original" and it takes 30+ seconds for the email to load which just shows the base64 encoded data
I tried to open in inbox in Outlook and after 5 minutes of the emails not loading I gave up (thinking the emails are not encoded properly or something causing outlook to get stuck)
It looks like it is working (i.e. the file looks legit based on the gmail icon preview) but I cant do anything else with it and I don't know if it is a Gmail issue or File Issue.
Any advice?
Turns out that Gmail was having issues all yesterday afternoon with attachments. It was a Gmail issue - The timing is unbelievable
https://www.theguardian.com/technology/2019/mar/13/googles-gmail-and-drive-suffer-global-outages

PHPMailer seems to not install correctly: Uncaught Error: Class 'PHPMailer\PHPMailer\PHPMailer

I am getting the error above when I run my code. Following the instructions on the PHPMAiler Github page, I added "phpmailer/phpmailer": "^6.0" to my composer.json but PHPMailer seems not to load.
I tried using $mail = new PHPMailer\PHPMailer\PHPMailer(true) instead of $Mail = new PHPMailer(true). I went to the Composer IRC channel to see if my problem was with Composer. I have also tried using the full path in the require 'vendor/autoload.php'; statement.
// 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;
//Load Composer's autoloader
require 'vendor/autoload.php';
//other code...
//Create a new PHPMailer instance
$mail = new PHPMailer(true);
I expect PHPMailer to run. Where did I go wrong?
When I had difficulty running PHPMailer on my local XAMPP server and the composer, I ended up installing the file manually by loading it into my directory
htdocs
-index.php
-Other_Program_to_run_with_PHPMailer.php
-folder(PHPMailer)
<?php
$messege=""
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'insert Username'; // SMTP username
$mail->Password = 'insert Password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('insert username', 'Information');
$mail->addAddress('who it is being sent to', 'PHP Management'); // Add a recipient
$mail->addReplyTo('who they can reply to', 'PHP Management');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = ;
$mail->Body = $message;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'The following Message has been sent';
echo $message;
}
?>
From there I have been copy and pasting onto my server and it works out pretty good.
Scott
Your problem may be solved if you would have read the documentations. Use the below code at first.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
just download the phpMailer Class from that GIT repo link
https://github.com/PHPMailer/PHPMailer
and extract/copy three files PHPMailer.php, Extension.php and SMTP.php files put them in a folder name : (PHPMailer) like in the image bellow :-
https://i.stack.imgur.com/T6DXW.png
and just add these lines of code at the top of your file
//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\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
// require 'vendor/autoload.php';
require('PHPMailer/Exception.php');
require('PHPMailer/SMTP.php');
require('PHPMailer/PHPMailer.php');

PHP mailer throws error in php 7 when tried send mail

I'm trying to send mail using PHP Mailer but I'm getting an error.
Kindly check my code let me know the fix.
Here is my code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
$mail = new PHPMailer;
try {
//Server settings
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'xxxxxxxxxxxx ';
$mail->Password = 'xxxxxxxxx';
//$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom('xxxxxxx', 'shiva');
$mail->addAddress('siva.sing.sivan#gmail.com', 'SP'); // Add a recipient
$mail->addAddress('senthil.mca2008#gmail.com', 'SK'); // Add a recipient
//\\$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('opensourcesivaprakash#gmail.com', 'Information');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Test mail form SP';
$mail->Body = 'This is the HTML message <b>From SP!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}else{
echo 'Message has been sent';
}
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
?>
My Error:
Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Please correct my code to fix the issue.
Hey #shiva use this $mail->SMTPSecure = 'tls' and use port as $mail->Port = 587 that's it!
Tell me it worked for you, if not then make sure to enable "Less Secure Apps" in your account settings, Thanks!
Let me know it worked for you or not?
upgrade the php version to 7.2.x and try it has inbuilt openssl 1.1.1

Resources