PHPMailer w/Gmail - Not Working - php

I have been recently learning PHP, and I need to be able to send emails using it.
I have found out that PHPMailer is a great way to send the mail, so I have tried it out. I have set up my code according to all of the examples that I can find, but I still am unable to get it to work.
Here is my PHP code:
<?php
error_reporting(E_ALL);
$fc = file_get_contents("http://redxtech.ca/fbm/");
echo $fc;
if (isset($_GET["name"]) && isset($_GET["email"]) && isset($_GET["m"])) {
$name = $_GET["name"];
$email = $_GET["email"];
$msg = $_GET["m"];
}
else {
$name = "Blank Name";
$email = "<email here>";
$msg = "Blank";
};
$e_msg = "FB:/nYou have recieved a new submission form from " . $name . " at <" . $email . ">./n/nIt says:/n/n" . $msg . "./n/nDo what you wish with this information./n~ Gabe";
require "PHPMailerAutoload.php";
$mail = new PHPMailer;
$mail->SMTPDebug = 1;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "<my gmail>";
$mail->Password = "<my super secret password>";
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->setFrom("<my gmail>", "Red's Mailer");
$mail->addAddress("<my other email>", "Gabe");
$mail->addAddress("<another email>", "FB");
$mail->addReplyTo("<my other email>", "Gabe");
$mail->isHTML = true;
$mail->Subject = "New Submission";
$mail->Body = $e_msg;
$mail->AltBody = "This is an altbody.";
if(!$mail->send()) {
echo "<script>console.log('Mail was not sent')</script>";
$errInf = $mail->ErrorInfo;
echo "<script>console.log('Mailer Error: " . $errInf . "')</script>";
} else {
echo "<script>console.log('Mail was sent')</script>";
}
?>
When I click on the submit button to send the form on the previous page, it takes me to /mail.php?name=aName&email=anEmail&m=aMsg and echo's the page, but it isn't sending the email.
When I open up Chrome Dev Tools:
"The devicemotion event is deprecated on insecure origins, and support will be removed in the future. You should consider switching your application to a secure origin, such as HTTPS. See for more details."
However, I'm pretty sure that is caused by the embedded Vimeo players and not PHPMailer.
If anyone can give me a hand here that would be great :D

I fixed my own problem.
When I mentioned that I didn't think it was loading properly, that was half correct.
To fix it, I added the rest of the .php files into the same directory as the autoloader. I thought that the autoloader automatically included all of them.

Related

Trying to redirect after form submit... cant change header Error

I've made a form file, where user can upload files with phpmailer. Everything is working fine...except i cant redirect. I know many people have asked this question before and i've really tried following all solutions provided, but I'm still stuck...
this is my php file that handles the form and I want it to redirect to my php/smarty file where the form itself is..
<?php
use PHPMailer\PHPMailer\PHPMailer;
require_once "../klassen/phpmailer/PHPMailer.php";
require_once "../klassen/phpmailer/SMTP.php";
require_once "../klassen/phpmailer/Exception.php";
if (isset($_POST['name']) && isset($_POST['email'])) {
$name = $_POST['name'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$msg = $_POST['msg'];
$mail = new PHPMailer();
//smtp settings
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "somemailadress";
$mail->Password = "password";
$mail->Port = 587;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
//email settings
$mail->isHTML(true);
$mail->setFrom($email);
$mail->addAddress("blabla#gmail.com");
$mail->subject = "$email ($name)";
$mail->Body =
$name .
$email .
$msg
;
$mail->AltBody =
' This is the body in plain text for non-HTML mail clients';
if (!empty($_FILES['attach'])) {
for ($i = 0; $i < count($_FILES['attach']['name']); $i++) {
$mail->addAttachment(
$_FILES['attach']['tmp_name'][$i],
$_FILES['attach']['name'][$i]
);
}
}
if ($mail->send()) {
error_reporting(E_ALL | E_WARNING | E_NOTICE);
ini_set('display_errors', TRUE);
flush();
header('Location: vacatures2.php');
die('should have redirected by now');
}
else {
echo 'Mailer error: ' . $mail->ErrorInfo;
}
}
Im getting following error
Warning: Cannot modify header information - headers already sent in /Applications/MAMP/htdocs/testarrays/scripts/contact.php on line 61
should have redirected by now
There s no indicator where it goes wrong, only that it fails at line 61 right?
Could the problem be with the php file its redirecting to?
Please help

Error Sending Emails using PHPMailer over SMTP

I've had a look around as to why my PHP script was not sending any emails when I had the $mail->isSMTP(); set.
Before I go into the problem, I would like to point out that I am using mailgun.org as my SMTP server. My PHP script is simple, I have an HTML form that forwards data to a PHP file which in turn calls the PHPMailer script and sends an email.
Here is the code to my PHP Script:
date_default_timezone_set('Asia/Manila');
require 'phpmailer/PHPMailerAutoload.php';
// include 'phpmailer/class.phpmailer.php';
// require 'phpmailer/class.smtp.php';
$mail = new PHPMailer;
//$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = "smtp.mailgun.org";
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = ""; //Username removed
$mail->Password = ""; //Password removed
$mail->setFrom('', ''); //Email address and Name removed
$mail->addReplyTo($userMail, $firstName);
$mail->addAddress('emailOne#example.com', 'Name'); //Actual Values Changed
$mail->addAddress('emailTwo#example.com', 'Name'); //Actual Values Changed
$mail->addAddress('emailThree#example.com', 'Name'); //Actual Values Changed
$mail->Subject = 'New Application for website by '. $firstName;
$mail->msgHTML($theMessage);
$mail->AltBody = $theMessage;
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else { //Some HTML code here
}
Now then, as you can see, I have commented out the $mail->isSMTP(); line. This is because whenever I try to use it, the code does not load, and after a long wait gives a 500 error. (Sadly, by cPanel setup does not allow me to view apache logs).
I tried importing just the class.phpmailer.php file, but that gave me a fatal error that the class SMTP was not defined, which was expected. I then included the class.smtp.php file which gave me the same 500 error.
I had a look around StackOverflow and came across this answer however it did not help my case.
I have had a look at Mailgun's logs, but they have no record of the script even trying to connect.
Additional Information: If it matters, I have the following files in the same directory:
- sendMail.php //The script above
- class.phpmailer.php
- class.smtp.php
- PHPMailerAutoload.php
- index.html //Not important in this situation.
I hope someone will be able to help me out, I'm relying on the non-smtp method for now. :/
Try this working fine..!
date_default_timezone_set('Asia/Manila');
require 'phpmailer/PHPMailerAutoload.php';
// include 'phpmailer/class.phpmailer.php';
// require 'phpmailer/class.smtp.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->Username = ""; //Username removed
$mail->Password = ""; //Password removed
$mail->addReplyTo($userMail, $firstName);
$mail->SetFrom('emailOne#example.com', 'my name');
$mail->Subject = 'New Application for website by '. $firstName;$mail->MsgHTML($theMessage);
$mail->AddAddress('aswad#yahoo.com', 'my name');
if($mail->Send()) {
echo "Message sent!";
}else {
echo "Mailer Error: " . $mail->ErrorInfo;
}

PHPMailer works on one page but doesn't work on similar

EDIT: Somehow the code only works on the webserver and not on localhost, so there's your "fix".
So, my php code works as it should like this:
require 'PHPMailer/PHPMailerAutoload.php';
$nome = $_POST["nome"];
$subject = $_POST["subject"];
$message = $_POST["message"];
$email = $_POST["email"];
$contacto = $_POST["contacto"];
$body = "<p>Mail recebido de: </p>" . $nome . "<p>Email:</p>" . $email . "<p> Contacto:</p>" . $contacto . "<p>Mensagem:</p>" . $message ;
$mail = new PHPMailer();
$mail->CharSet = "text/html; charset=UTF-8;";
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->CharSet = 'UTF-8';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = "the email";
$mail->Password = the password;
$mail->SetFrom('the email', 'Organizer');
$mail->Subject = "[ORÇAMENTO] " . $subject;
$mail->Body = $body;
$mail->IsHTML(true);
$mail->AddAddress("the email");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
$sucesso = 'Mensagem enviada com sucesso!';
}
this first script sends the email to itself, but even that doesn't work here ($mail->Send() = 1, still I don't receive the email):
require '../PHPMailer/PHPMailerAutoload.php';
$body = "<p>Car(a) " . ${'user' . $i} . ",</p> <p> Foi lhe associado(a) uma nova ocorrência. Consulte-a em http://www.organizer.com.pt . </p>";
$mail = new PHPMailer();
$mail->CharSet = "text/html; charset=UTF-8;";
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->CharSet = 'UTF-8';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = "the email";
$mail->Password = the password;
$mail->SetFrom('the email', 'Organizer');
$mail->Subject = "Nova Ocorrência";
$mail->Body = $body;
$mail->IsHTML(true);
$mail->AddAddress($email);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
$sucesso = 'Mensagem enviada com sucesso!';
}
I have tested all the variables that I get from the database and so on and they are all correct, I just don't receive the email for some reason. Anyone can help?
P.S.: Sorry some of this is in portuguese, I think the code is still perfectly understandable.
"Doesn't work" is not a useful problem description. On SO, detail is everything.
It doesn't help that you've based your code on an obsolete & incorrect example and have not read the docs, and I suspect you are using an old version of PHPMailer too since it would have provided you with a link to relevant docs if it was a recent version. So before anything else, get the latest version and read the docs.
As for specific problems: SMTPSecure = 'ssl' with Port = 587 will not work. Port 587 is used for SMTP+STARTTLS, not implicit SSL, so set SMTPSecure = 'tls'.
This is just wrong:
$mail->CharSet = "text/html; charset=UTF-8;";
Your other script does it right:
$mail->CharSet = 'UTF-8';
If you're having trouble with something that has a debug option, enable it!
$mail->SMTPDebug = 2;
Increase that to 3 if you have initial connection problems.
I'd like to know where you got that example code so I can ask the authors to delete or update it; having broken, obsolete examples lying around just wastes everybody's time.

PHP Mailer - Internal Server Error

I have been trying to make the contact form on my website to work and I've spent weeks trying to figure it out and I couldn't.
Here's the problem - I purchased a web template and it came with the PHPMailer. I'm now done plugging my content into the template, but the contact form has been a pain. I've followed the instructions the best I know on the PHP file, but it's giving me an "Internal Server Error" when I am testing the contact form.
Here's the code that came with my purchase:
$name = trim($_POST['name']);
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$site_owners_email = 'name#mydomain.com'; // Replace this with your own email address
$site_owners_name = 'My Name'; // Replace with your name
try {
require_once('/Beta-BRC/php/PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "[WEB Form] ".$subject;
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Mailer = "smtp";
$mail->Host = "smtp.gmail.com"; // Replace with your SMTP server address
$mail->Port = 465;
$mail->SMTPSecure = "SSL";
$mail->SMTPAuth = true; // Turn on SMTP authentication
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
//echo "true";
if($mail->Send()) {
echo "true";
} else {
echo "Error sending: " . $mail->ErrorInfo;
}
} catch (Exception $e) {
echo $e;
}
Quick note - I've alrealy tried using a GMAIL account on this part but it still does not work.
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
There's no need to log into Gmail with phpmailer. Below is an example of my phpmailer function using the default settings.
public function sendEmail($toaddress,$toname,$subject,$message){
if($template = file_get_contents('/home/username/domains/mydomain.com/public_html/html/email-template.html')){
$template = str_replace("[SUBJECT]",$subject,$template);
$template = str_replace("[CONTENT]",nl2br($message),$template);
$mailer = new PHPMailer;
$mailer->XMailer = "Organization Name 4.0.0";
if($this->is_logged_in()){
$mailer->AddCustomHeader("X-Originating-User-ID",$this->acct['id']);
}
$mailer->AddCustomHeader("X-Originating-IP",$_SERVER['REMOTE_ADDR']);
$mailer->setFrom("outbound#mydomain.com","From Name");
$mailer->AddAddress($toaddress,$toname);
$mailer->Subject = $subject;
$mailer->MsgHTML($template);
$mailer->AltBody = $message;
return $mailer->Send();
}else{
return false;
}
}
The email address listed doesn't actually exist. The email is just being sent from my server and phpmailer just says it's from that email address.
Try modifying my function to suit your needs and let me know how that works.
Note: You'll need to make sure your mail server is turned on for this to work
Although you don't have to use my function at all. Try debugging your code by checking some error logs on your server. Typically in the apache error logs (if you're running apache, however). Checking error logs is a huge part of troubleshooting your code and often can help you become more proactive.
I hope this helps even the slightest!
The specific cause of the Internal Server Error is the incorrect path you've supplied to the require_once statement that loads the PHPMailer class.
The path you've supplied is /Beta-BRC/php/PHPMailer/class.phpmailer.php, where the correct statement should be
require_once('/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
or perhaps more generally:
require_once($_SERVER['DOCUMENT_ROOT'].'/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
You've provided effectively a URL, but PHP requires the path in the server file system, which is not the same.
That should get you past this error. It's possible that there are others.

PHPMailer fails to send

I see most PHPMailer questions use IsSMTP(), but I'm working from a very basic example I found yesterday on SO (can't seem to find the link in History though) that doesn't.
require_once("class.phpmailer.php");
$email = new PHPMailer();
if (isset($_FILES['upload']['size']))
{
echo 'file size: '.(basename($_FILES['upload']['size'])* 1024).'<br />';
if (move_uploaded_file($_FILES['upload']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['upload']['name'])." has been uploaded<br />";
$email->AddAttachment($target_path);
}
else
{
echo "There was an error uploading the file, please try again!<br /> ".basename($_FILES['upload']['error']);
}
}
else
{
echo "No file was found for the upload.<br />";
}
$email->To = "me#this.com";
$email->From = $email_from;
$email->FromName = $first_name;
$email->Subject = "Query from website";
$email->Body = $email_message;
//echo "mail built...<br />";
if (!$email->Send())
{
echo "Mailer error: " . $email->ErrorInfo;
}
I've tried sending twice. The code executes fine and the last if statement returns true.
Do I have to use IsSMTP()? If so, does it have to route through SSL like I've seen suggested here?
Thanks in advance?
EDIT
I've added details required for SMTP as follows:
$email->IsSMTP();
$email->Host = "localhost";
$email->Port = 465;
$email->SMTPAuth = true;
$email->Username = "bacon";
$email->Password = "4ndCh33se";
This doesn't seem to have triggered it to send. There also still isn't any error reported.
EDIT
Turns out there was an error, I had a redirect in a weird place that was preventing me from seeing it. The error is as follows:
You must provide at least one mailer is not supported.
Initially, the addition of the IsSMTP() seemed vital and was implemented as per other answers.
All answers failed, however, to address one missing piece of the puzzle.
PHPMailer requires at least 1 address to be added as per below. I just used the same address here as was set in the To property:
$email->To = "me#this.com";
$email->AddAddress("me#this.com");
Once this was done, all worked perfectly fine.
if you want to send mail through smtp you need to set SMTP username and password and other setting.
And also you need to add IsSMTP().
Example Gmail SMTP setup
$this->SwiftMailer->smtpType = 'tls';
$this->SwiftMailer->smtpHost = 'smtp.gmail.com';
$this->SwiftMailer->smtpPort = 587;
$this->SwiftMailer->smtpUsername = 'emailaddress#gmail.com';
$this->SwiftMailer->smtpPassword = 'gmailPassword';
$this->SwiftMailer->sendAs = 'html';
$this->SwiftMailer->from = 'sender#gmail.com';
$this->SwiftMailer->fromName = 'Sender Name';
$this->SwiftMailer->to = "receiver#anything.com";
$this->Email->sendAs = 'html';
$email->To = "me#this.com";
$email->From = $email_from;
$email->FromName = $first_name;
$email->Subject = "Query from website";
$email->Body = $email_message;
I have the following besides yours. Maybe it helps:
$email->IsSMTP(); // set mailer to use SMTP
$email->Host = "mail.webaddress.com"; // specify main and backup server
$email->SMTPAuth = true; // turn on SMTP authentication
$email->Username = "********"; // SMTP username
$email->Password = "********"; // SMTP password
I have changed nothing in class.phpmailer.php
Try this
$email->IsSMTP(); // set mailer to use SMTP
$email->Host = "mail.webaddress.com"; // specify main and backup server
$email->SMTPAuth = false; // turn on SMTP authentication
$email->Port = 25
$email->SMTPSecure = "";
$email->Username = "********"; // SMTP username
$email->Password = "********"; // SMTP password

Categories