I can't get PHP Mailer to work

I am trying to follow an online tutorial which would allow me to send an email using PHP Mailer. I previously had some problems with my hosting company not supporting php mail() but this has been resolved and I am now able to send an email using a script which uses php mail().  However, I've been advised to use PHP Mailer, so started following a tutorial. As far as I can understand I've followed all the steps in the tutorial and the following should work.  The code is below....

I am testing this on my live server and WAMP developer server and having no success at either.  Any advice or guidance would be really appreciated with this. I have been really struggling over the past couple of weeks to create a page which sends emails.

Many thanks

<?php



$msg = "";
	use PHPMailer\PHPMailer\PHPMailer;
	include_once "PHPMailer/PHPMailer.php";
	include_once "PHPMailer/Exception.php";
	include_once "PHPMailer/SMTP.php";


if (isset ($_POST['submit'])) {
	$subject=$_POST['subject'];
	$email=$_POST['email'];
	$message = $_POST['message'];
	

		
	if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != "") {
	
										//$_FILES is a global variable we use when sending attachments
	$file = "attachment/" . basename($_FILES['attachment']['name']); // - The basename() function returns the filename from a path. https://www.w3schools.com/php/func_filesystem_basename.asp
										//we are uploading to "attachment" folder

	move_uploaded_file($_FILES['attachment']['tmp_name'], $file); //The move_uploaded_file() function moves an uploaded file to a new location. move_uploaded_file(file,newloc)This function returns TRUE on success, or FALSE on failure. https://www.w3schools.com/php/func_filesystem_move_uploaded_file.asp
	}
	
	else
			$file = "";

	$mail = new PHPMailer();

		//if we want to send via SMTP
		$mail->Host = "smtp.gmail.com";
	    $mail->isSMTP();
		$mail->SMTPAuth = true;
		$mail->Username = "henryswanson@gmail.com";
		$mail->Password = "(MY PASSWORD FOR THE ABOVE EMAIL ADDRESS)";
		$mail->SMTPSecure = "ssl"; //TLS
		$mail->Port = 465; //587

		$mail->addAddress('hello@codingpassiveincome.com');
		$mail->setFrom($email);
		$mail->Subject = $subject;
		$mail->isHTML(true);
		$mail->Body = $message;
		$mail->addAttachment($file);

		if ($mail->send())
		    $msg = "Your email has been sent, thank you!";
		else
		    $msg = "Please try again!";

		unlink($file);
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Contact Form AY</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
	<div class="container" style="margin-top: 100px">
		<div class="row justify-content-center">
			<div class="col-md-6 col-md-offset-3" align="center">
				<img src="images/logo.png"><br><br>

                <?php if ($msg != "") echo "$msg<br><br>"; ?>

				<form method="post" action="sendemail.php" enctype="multipart/form-data"> <!--use enctype as we are sending an attachement-->
					<input class="form-control" name="subject" placeholder="Subject..."><br>
					<input class="form-control" name="email" type="email" placeholder="Email..."><br>
					<textarea placeholder="Message..." class="form-control" name="message"></textarea><br>
					<input class="form-control" type="file" name="attachment"><br>
					<input class="btn btn-primary" name="submit" type="submit" value="Send Email">
				</form>
			</div>
		</div>
	</div>
</body>
</html>

Open in new window

AdamTrying to learn phpAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
I haven't gone through your entire code but 2 things of note.

Firstly, you're trying to use the Mailer class before you've actually included it.

Secondly, as you're debugging at the moment, I would turn on error reporting, and then create a script that just sends a simple email - forget about your form and file uploads. Just get an email to send:

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

include_once "PHPMailer/PHPMailer.php";
include_once "PHPMailer/Exception.php";
include_once "PHPMailer/SMTP.php";

use PHPMailer\PHPMailer\PHPMailer;

$msg = "Just a simple test message";

...

Open in new window

1
Marcus BointonCommented:
You don't actually say what's wrong... Following the troubleshooting guide might help.

Is there any particular reason you're not using composer? I'd also recommend basing your code on the examples provided with PHPMailer, like this one that's very similar to what you're doing.

BTW `use` directives do usually (by convention) precede include/require statements. They don't actually do anything or require classes to exist, it's just a way of bringing externally namespaced names into your own namespace.
0
AdamTrying to learn phpAuthor Commented:
Thanks Chris, Marcus for the reply.

Sorry - the issue is that no email is received at the email address specified - henryswanson@gmail.com, and that after I press submit I get the message  "Please try again!" - suggesting an issue with
($mail->send())
somewhere.

 if ($mail->send())
		    $msg = "Your email has been sent, thank you!";
		else
		    $msg = "Please try again!";

Open in new window


The reason I avoided using Composer was just because I'm trying to follow the exact steps as per the tutorial (which doesn't install it). Also, I avoided it for the time being as to me, it just represented another layer of complexity. I'm sure there are benefits, and once I get this tutorial to work I'll give Composer a try.

Chris, I have updated as per your suggestion and removed the file attachment part of the code and the error messaging.  Still the same lack of success however. Where would I expect to see the output from the error reporting bit? Updated Code below.

Thanks.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
//$mail->SMTPDebug = 2;

use PHPMailer\PHPMailer\PHPMailer;

include_once "PHPMailer/PHPMailer.php";
include_once "PHPMailer/Exception.php";
include_once "PHPMailer/SMTP.php";



$msg = "Just a simple test message";



if (isset ($_POST['submit'])) {
	$subject=$_POST['subject'];
	$email=$_POST['email'];
	$message = $_POST['message'];
	$mail = new PHPMailer();

		//if we want to send via SMTP
		$mail->Host = "smtp.gmail.com";
	    $mail->isSMTP();
		$mail->SMTPAuth = true;
		$mail->Username = "henryswanson@gmail.com";
		$mail->Password = "Burton1976";
		$mail->SMTPSecure = "ssl"; //TLS
		$mail->Port = 465; //587

		$mail->addAddress('adamyounis@yahoo.com');
		$mail->setFrom($email);
		$mail->Subject = $subject;
		$mail->isHTML(true);
		$mail->Body = $message;
		

		if ($mail->send())
		    $msg = "Your email has been sent, thank you!";
		else
		    $msg = "Please try again!";

		
}

?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Contact Form AY</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
	<div class="container" style="margin-top: 100px">
		<div class="row justify-content-center">
			<div class="col-md-6 col-md-offset-3" align="center">
				<img src="images/logo.png"><br><br>

                <?php if ($msg != "") echo "$msg<br><br>"; ?>

				<form method="post" action="sendemail_test.php" enctype="multipart/form-data"> <!--use enctype as we are sending an attachement-->
					<input class="form-control" name="subject" placeholder="Subject..."><br>
					<input class="form-control" name="email" type="email" placeholder="Email..."><br>
					<textarea placeholder="Message..." class="form-control" name="message"></textarea><br>
				
					<input class="btn btn-primary" name="submit" type="submit" value="Send Email">
				</form>
			</div>
		</div>
	</div>
</body>
</html>

Open in new window

0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Marcus BointonCommented:
It would really help to show debug output, and in that code that checks for send success, output what's in `$mail->ErrorInfo`, since that will contain a message saying why it failed (as all the examples do). It's quite likely you have a TLS problem because of outdated CA certificates, but that is harder to diagnose when using SMTPS (port 465); Try setting `SMTPSecure = 'tls'` and `Port = 587` to get more feedback.
1
AdamTrying to learn phpAuthor Commented:
Thanks Marcus.

I think I've followed what you suggested, but not entirely sure. I updated the code with $mail->ErrorInfo if  ($mail->send()) doesn't return true and changed the TLS and port settings. I noticed no difference though. Should I be going to a log file for error reporting or something?

updated code below:
<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
//$mail->SMTPDebug = 2;

use PHPMailer\PHPMailer\PHPMailer;

include_once "PHPMailer/PHPMailer.php";
include_once "PHPMailer/Exception.php";
include_once "PHPMailer/SMTP.php";



$msg = "Just a simple test message";



if (isset ($_POST['submit'])) {
	$subject=$_POST['subject'];
	$email=$_POST['email'];
	$message = $_POST['message'];
	$mail = new PHPMailer();

		//if we want to send via SMTP
		$mail->Host = "smtp.gmail.com";
	    $mail->isSMTP();
		$mail->SMTPAuth = true;
		$mail->Username = "henryswanson@gmail.com";
		$mail->Password = "my password for henryswanson@gmail.com ";
		$mail->SMTPSecure = "tls";
		$mail->Port = 587;

		$mail->addAddress('adamyounis@yahoo.com');
		$mail->setFrom($email);
		$mail->Subject = $subject;
		$mail->isHTML(true);
		$mail->Body = $message;
		

		if ($mail->send())
		    $msg = "Your email has been sent, thank you!";
		else
		$mail->ErrorInfo;    
		$msg = "Please try again!";
			

		
}

Open in new window


thanks.
0
Chris StanyonWebDevCommented:
You need to echo out the ErrorInfo, not just call it.

Just tried this myself and found that you'll also need to ensure your Google Account is setup to allow Less Secure Apps to use it. Your test code should look something like this. It will attempt to send a very simple text email. If it fails, it will report the errors

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include_once "PHPMailer/PHPMailer.php";
include_once "PHPMailer/Exception.php";
include_once "PHPMailer/SMTP.php";

use PHPMailer\PHPMailer\PHPMailer;

$mail = new PHPMailer();

$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->IsHTML(false);
$mail->Username = "yourEmailAddress";
$mail->Password = "yourPassword";
$mail->SetFrom("yourEmailAddress");
$mail->Subject = "Test Message";
$mail->Body = "This is a simple test message";
$mail->AddAddress("adamyounis@yahoo.com");

if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message has been sent";
}

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Dave BaldwinFixer of ProblemsCommented:
Gmail doesn't like PHPMailer and it's 'auth' methods.  Yahoo isn't fond of it either.  Since they can tell that you are sending from a web server instead of an email server, they are often difficult to use.  That's because historically most spam has come from web servers, not from email servers.

I have used PHPMailer with many other SMTP providers without any problems.
0
Dave BaldwinFixer of ProblemsCommented:
By the way, the samples provided with PHPMailer work perfectly with the right info and SMTP server.
1
Marcus BointonCommented:
PHPMailer's auth methods are standard RFC methods, indistinguishable from anyone else, and they have no way of telling if you're a mail client/server or a web server - it's just a TCP connection on a submission port. The only time they can tell is by spotting the "X-Mailer" header within a message - which isn't sent until long after auth has completed.

The "less secure apps" thing is really pretty bogus - it's Google's term for "not OAuth", and it's not really any less secure at all. PHPMailer supports XOAUTH2 anyway, so you don't have to use the less secure apps setting - but like everything related to OAuth (IME), it is deeply unpleasant, wildly inconsistent, and overcomplicated to use.

Meanwhile, back on the question, because this sounds like a connection-level problem, you should set `SMTPDebug = 3`, however, if you're having problems connecting at all, your ISP may be blocking outbound SMTP and you'll get no feedback beyond a connection failure. The telnet and openssl tests described in the guide can help diagnose the problem more thoroughly.
1
Dave BaldwinFixer of ProblemsCommented:
they have no way of telling if you're a mail client/server or a web server
Sorry but that's not true.  Google knows every single IP and hostname and what their purpose is.  Microsoft and Yahoo do too.  Extensive experiments by me have convinced me that they know and care.
0
Marcus BointonCommented:
Nope. I can send as an MUA, MTA, and web server simultaneously, from the same IP, and quite often do. For any single connection, they cannot tell what you are using because they look identical. Sending reputations are an entirely different issue, but they only apply in aggregate over long periods and high volumes.
0
AdamTrying to learn phpAuthor Commented:
Many thanks Chris and and Marcus with your help with this.

Using the cut down test script  with error output you gave me Chris, and changing the settings in Google, I was able to see where the problems were occurring.

The error message suggested an issue with my username and password supplied.

I am embarrassed to say that the login credentials were actually incorrect. Not sure if that was the only issue, but with the settings changed in Google, and the login credentials corrected, the basic script work. I will now build on this.

Many thanks for your help with this. Learning how to output an error message has greatly helped here and will no doubt help me in the future. Wish you both a great weekend and again, many thanks.
1
Chris StanyonWebDevCommented:
No worries Adam. Glad you got it sorted.

Learning how to 'see' what's going on in your script, for example with error reporting, error handling, logging, var_dumps, debugging, is a vital skill and if you know that, then coding gets a lot easier :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Development

From novice to tech pro — start learning today.