I have the following code to send an email with phpMailer. What I don't understand is why the email is sent and everything is OK even if I use a wrong password. In that case, the headers of the email give this answer (adapted from real case): X-PHP-Originating-Script: 532:class.phpmailer.php
How can I force the login error to appear and avoid the email being sent anyway? I guess that this has something to do with the class using other methods after trying to connect to the SMTP server. I don't want the email to be sent in ALL cases, if the password has changed or service not available, I want to know it and the script to stop and throw error. I use the latest available version of the class.
require 'phpmailer/class.phpmailer.php';
$to = "someone-email#example.com";
$subject = "Hello World";
$body = "HELLO WORLD";
$mail = new PHPMailer;
$mail->Host = "mail.example.com";
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->Username = "example#example.com";
$mail->Password = "**********";
$mail->From = "example#example.com";
$mail->FromName = "TEST";
$mail->AddReplyTo($to);
$mail->addAddress($to);
$mail->Subject = $subject;
$mail->MsgHTML($body);
if(!$mail->Send())
{
echo "KO " . $mail->ErrorInfo;
return false;
}
else
{
echo "OK";
return true;
}
You aren't using SMTP so I guess it's defaulting to mail(), which doesn't accept authentication.
To enable SMTP:
$mail->IsSMTP();
Related
Instead of using php's mail() function, I've been trying to set up PHPMailer with no success. I put in "echo here" for debugging purposes, and that is all it shows. I do not get any emails, or the sent or error messages. I'm stumped, and after researching it on here may switch to swift mailer. I'd really like to know what I screwed up though.
In my code, address is set to my email, and the username and password are set to a dummy account I made.
<?php
include('class.phpmailer.php');
$mail = new PHPMailer();
$address = "test#gmail.com";
$body = "test email";
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = "username#gmail.com";
$mail->Password = "password";
$mail->SetFrom('name#yourdomain.com', 'Web App');
$mail->Subject = "A Transactional Email From Web App";
$mail->MsgHTML($body);
$mail->AddAddress($address, $name);
echo "Here";
if($mail->Send()) {
echo "Message sent!";
}
else {
echo "Mailer Error: " ; $mail->ErrorInfo;
}
?>
As you are using Gmail I think you must make sure the gmail account has the insecure application auth activated
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.
I am trying to setup PHPMailer for a customer. He has his own mail server located at a certain IP address. When asked to give me the information to send email through the system, he gave the following:
Host: xx.xxx.x.x
Port: 25
Domain: mydomain.local
Username: myemail#mydomain.local
Password: <myemailpassword>
From: myemail#anotherdomain.xx
(Which he confirmed is being used for external email sending)
I tried to setup PHPMailer by setting the parameters to the exact namings above.
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "xx.xxx.x.x";
$mail->Port = 25;
$mail->Username = "myemail#mydomain.local";
$mail->Password = <myemailpassword>;
$mail->SetFrom('myemail#anotherdomain.xx', 'Webname');
$mail->[...]
I got the following error:
Failed to connect to server (0)
So I try to send an email through telnet to check if it's the customer's email server or the PHPMailer settings:
telnet xx.xxx.x.x 25
It goes through, I'm connected to the server.
helo mydomain.local
I'm getting 'Hello' as a reply. This leads me to believe it might be the PHPMailer settings that are wrong here.
I also try not using SMTP:
$mail->Host = "ssl://xx.xxx.x.x";
$mail->Port = 25;
$mail->Username = "myemail#mydomain.local";
$mail->Password = "password";
$mail->SetFrom('myemail#anotherdomain.xx', 'Webname');
$mail->[...]
Again no go. Am I going about this wrong? I'm only familiar with setting up PHPMailer to use Gmail before so I'm at a loss as to what could be the issue because I'm using a 'personal' email server.
Thanks Loadparts for your assistance.
I'm still not sure what the issue was but it seems it has resolved itself. It might have been from the email server side because coding wise, I didn't change anything. This is the final code I used.
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Port = 25;
$mail->Host = "xx.xxx.x.x"; // SMTP server
$mail->Username = "myemail#mydomain.local";
$mail->Password = <myemailpassword>;
$mail->From = "myemail#anotherdomain.xx";
$mail->FromName = <Web_Name>;
$mail->AddAddress("email#domain.com");
$mail->Subject = <Subject>;
$mail->AltBody = <Alt_Body>
$mail->WordWrap = 80;
$body = "test message";
$mail->MsgHTML($body);
$mail->IsHTML(true);
$mail->Send();
I use a test function that I know works 100% to test the email servers when using PHPMailer.
I'm not sure why you are having your problem, but try to use the function I have ( I know it's messy but it does the trick). Just replace all the XXXX with your info and make sure you have both class.phpmailer.php and class.smtp.php in the same folder.
<?php
error_reporting(E_ALL);
$toemail = 'XXXX';
$toname = 'XXXX';
$subject = 'Testing Email Sending...';
$bodyhtml = '<H1>yeah</h1>';
$bodytext = 'heres Hoping it works';
$fromemail = 'XXXX';
$fromname = 'XXXX';
var_dump(sendemail($toemail,$toname,$subject,$bodyhtml,$bodytext,$fromemail,$fromname));
function sendemail($toemail,$toname,$subject,$bodyhtml,$bodytext,$fromemail,$fromname)
{
require_once("class.phpmailer.php");
$mail = new phpmailer();
$mail->IsSMTP();
$mail->From = $fromemail;
$mail->FromName = $fromname;
$mail->Host = "XXXX";
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "XXXX"; // SMTP username
$mail->Password = "XXXX"; // SMTP password
$mail->Port="25";
$mail->SMTPDebug=true;
if(strlen($bodyhtml)>0) {
$mail->Body = $bodyhtml;
$mail->IsHTML(true);
}
else if(strlen($bodytext)>0){
$mail->Body = $bodytext;
}
if(strlen($bodytext)>0 && strlen($bodyhtml)>0){
$mail->AltBody = $bodytext;
}
$mail->AddReplyto($fromemail,$fromname);
$mail->Subject = $subject;
// Check if multiple recipients
if(preg_match("/;/",$toemail))
{
$tmp_email=preg_split("/;/",$toemail);
$tmp_contact=preg_split("/;/",$toname);
$mail->AddAddress($tmp_email[0], $tmp_contact[0]);
// echo "<!-- multi email:".$tmp_email[0]." contact:".$tmp_contact[0]." -->\n";
for($j=1;$j<count($tmp_email);$j++)
{
if(preg_match("/\#/",$tmp_email[$j]))
{ $mail->AddCC($tmp_email[$j], $tmp_contact[$j]);
// echo "<!-- multi email cc:".$tmp_email[$j]." contact:".$tmp_contact[$j]." -->\n";
}
}
}
else{
$mail->AddAddress($toemail, $toname);
}
$error= false;
if($mail->Send()){
$error =true;
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
return $error;
}
If this doesn't work, my first try would be using port 80 - which usually isn't blocked, then you can work on getting SSL to work.
PS: because it's a local domain, you may want to consider adding the domain to your /etc/hosts just to be sure.
Best of Luck!
I am trying to let users fill out a contact form, which will then be sent to my email. But its not working for some reason. I just get a blank page with no error message or any text and email is also not sent.
if (isset($_POST['submit']))
{
include_once('class.phpmailer.php');
$name = strip_tags($_POST['full_name']);
$email = strip_tags ($_POST['email']);
$msg = strip_tags ($_POST['description']);
$subject = "Contact Form from DigitDevs Website";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
//$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "info#example.com"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress('info#example.com', 'Information');
$mail->AddReplyTo($email, 'Wale');
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $msg;
$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;
}
echo 'Message has been sent';
You need to call:
$mail = new PHPMailer(true); // with true in the parenthesis
From the documentation:
The true param means it will throw exceptions on errors, which we need
to catch.
Its working now, i didnt include the 'class.smtp.php' file. The working code is below:
if (isset($_POST['submit']))
{
include_once('class.phpmailer.php');
require_once('class.smtp.php');
$name = strip_tags($_POST['full_name']);
$email = strip_tags ($_POST['email']);
$msg = strip_tags ($_POST['description']);
$subject = "Contact Form from DigitDevs Website";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
//$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "info#example.com"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress('info#example.com', 'Information');
$mail->AddReplyTo($email, 'Wale');
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $msg;
$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;
}
echo 'Message has been sent';
I had the same problem with no error message even with SMTPDebug enabled. After searching around for working examples I noticed that I didn't include the SMTP Secure value. Try adding this line:
$mail->SMTPSecure = 'ssl'; //secure transfer enabled
Work like a charm now.
I had a similar problem. In reference to #Syclone's answer. I was using the default "tls".
$mail->SMTPSecure = 'tls';
After I changed it to
$mail->SMTPSecure = 'ssl';
It worked ! My mailserver was only accepting connections over SSL.
What worked for me was setting From as Username and FromName as $_POST['email']
Hope this helps
PHPMailer use exception.
Try this
try {
include_once('class.phpmailer.php');
$name = strip_tags($_POST['full_name']);
$email = strip_tags ($_POST['email']);
$msg = strip_tags ($_POST['description']);
$subject = "Contact Form from DigitDevs Website";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
//$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "info#example.com"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress('info#example.com', 'Information');
$mail->AddReplyTo($email, 'Wale');
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $msg;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->Send();
exit;
} catch (phpmailerException $e) {
echo $e->errorMessage(); //error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage();
}
I was trying to load an HTML file to send, which did not belong to the www-data group on my Ubuntu server.
chown -R www-data *
chgrp -R www-data *
Problem solved!
I was debating whether to write my own handler or crow-bar PHPMailer into my existing class structure. In the event it was very easy because of the versatility of the spl_autoload_register function which is used within the PHPMailer system as well as my existing class structure.
I simply created a basic class Email in my existing class structure as follows
<?php
/**
* Provides link to PHPMailer
*
* #author Mike Bruce
*/
class Email {
public $_mailer; // Define additional class variables as required by your application
public function __construct()
{
require_once "PHPMail/PHPMailerAutoload.php" ;
$this->_mailer = new PHPMailer() ;
$this->_mailer->isHTML(true);
return $this;
}
}
?>
From a calling Object class the code would be:
$email = new Email;
$email->_mailer->functionCalls();
// continue with more function calls as required
Works a treat and has saved me re-inventing the wheel.
Try this ssl settings:
$mail->SMTPSecure = 'tls'; //tls or ssl
$mail->SMTPOptions = array('ssl' => array('verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true));
I am rather puzzled with this one.
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
if($mail->Send())
{
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->ClearCustomHeaders();
...
$mail->From = "DO_NOT_REPLY#...";
$mail->FromName = "****";
$mail->AddAddress($ToEmail1, "***"); //To: (recipients).
$mail->AddAddress($ToEmail2, "***"); //To: (recipients).
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $notification_subject;
$mail->Body = $notification_msg;
if($mail->Send())
{
...
The first email sends fine. The second one doesn't. What could be the reason for that behavior? Am I missing some kind of reset?
Update: using a different mail server seems to work so apparently it's a setting of that specific mail server causing problems. Any idea what that could be?
Some providers impose restrictions on the number of messages that can be sent within a specific time span. To determine if your problem depends by a provider "rate limit", you should try to add a pause after the first send. For example:
if ($mail->Send()) {
sleep(10); // Seconds
...
if ($mail->Send()) {
...
}
}
Then, by progressively lowering the sleep time, you should be able to determine which is the rate limit.
Try this:
As #Felipe Alameda A mentioned Remove $mail->SMTPKeepAlive = true;
// for every mail
if(!$mail->Send())
{
echo 'There was a problem sending this mail!';
}
else
{
echo 'Mail sent!';
}
$mail->SmtpClose();
IMHO you need to create new PHPMailer object for every sent email. If you want to share some common setup, use something like this:
$mail = new PHPMailer();
/* Configure common settings */
while ($row = mysql_fetch_array ($result)) {
$mail2 = clone $mail;
$mail2->MsgHTML("Dear ".$row["fname"].",<br>".$cbody);
$mail2->AddAddress($row["email"], $row["fname"]);
$mail2->send();
}
I think your problem is $mail->SMTPAuth = false;
It is hard to believe there are ISP or SMTP providers that don't require authentication, even if they are free.
You may try this to check for errors instead of or in addition to checking for send() true:
if ( $mail->IsError() ) { //
echo ERROR;
}
else {
echo NO ERRORS;
}
//Try adding this too, for debugging:
$mail->SMTPDebug = 2; // enables SMTP debug information
Everything else in your code looks fine. We use PHPMailer a lot and never had any problems with it
The key may lie in the parts you have omitted. Is the domain of the sender of both emails the same? Otherwise the SMTP host may see this as a relay attempt. If you have access to the SMTP server logs, check these; they might offer a clue.
Also, check what $mail->ErrorInfo says... it might tell you what the problem is.
i personally would try to make small steps like sending same email.. so just clear recipients and try to send identical email (this code works for me). If this code passes you can continue to adding back your previous lines and debug where it fails
and maybe $mail->ClearCustomHeaders(); doing problems
//SMTP servers details
$mail->IsSMTP();
$mail->Host = "mail.hostserver.com";
$mail->SMTPAuth = false;
$mail->Username = $myEmail; // SMTP usr
$mail->Password = "****"; // SMTP pass
$mail->SMTPKeepAlive = true;
$mail->From = $patrickEmail;
$mail->FromName = "***";
$mail->AddAddress($email, $firstName . " " . $lastName);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $client_subject;
$mail->Body = $client_msg;
// all above is copied
if($mail->Send()) {
sleep(5);
$mail->ClearAllRecipients();
$mail->AddAddress('another#email.com'); //some another email
}
...
Try with the following example.,
<?php
//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = file_get_contents('contents.html');
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.yourdomain.com"; // 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 = "mail.yourdomain.com"; // sets the SMTP server
$mail->Port = 26; // set the SMTP port for the GMAIL server
$mail->Username = "yourname#yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","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
$mail->MsgHTML($body);
$address1 = "whoto#otherdomain.com";
$address2 = "whoto#otherdomain.com";
$mail->AddAddress($address1, "John Doe");
$mail->AddAddress($address2, "John Peter");
$mail->AddAttachment("images/phpmailer.gif"); // attachment if any
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment if any
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
Note : Better you can make a multiple user email and name as an ARRAY, like
<?php
$recipients = array(
'person1#domain.com' => 'Person One',
'person2#domain.com' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
(or)
foreach($recipients as $email => $name)
{
$mail->AddAddress($email, $name);
}
?>
i think this may help you to resolve your problem.
I think you've got organizational problems here.
I recommend:
Set your settings (SMTP, user, pass)
Create new email object with info from an array holding messages and to addresses
Send email
Goto step 2