I have a problem with my code, the intension is to send an email using smtp.mandrill.com and use the alert to know when the email is sended, otherwise send another alert when fails to send the email. And I recived the alert confirming the email, but is'nt sended. If anyone knows the problem I thanks a lot your help.
This is the code.
<?php
$name = $_POST["first_name"];
$telefono = $_POST["telephone"];
$texto = $_POST["text"];
$body =
"Name: ".$name."<br>
Telephone: ".$telephone."<br>
Message: ".$text;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPmailer/Exception.php';
require 'PHPmailer/PHPMailer.php';
require 'PHPmailer/SMTP.php';
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0; //"2" Enable verbose debug output. Change to "0" to hide all the letters n.n
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.mandrill.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'example#example.com'; //SMTP username
$mail->Password = 'Any API key'; //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
$mail->Port = 465;
//Recipients
$mail->setFrom('example#example', 'Example');
$mail->addAddress('example#example'); //Add a recipient
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Contact';
$mail->Body = 'New message from <b>Contact</b><br><br>'.$body;
$mail->CharSet = 'UTF-8';
$mail->send();
echo '<script>
alert("The data was sent successfully.");
window.history.go(-1);
</script>';
} catch (Exception $e) {
echo '<script>
alert("An error occurred while sending the data.");
window.history.go(-1);
</script>';
}
?>
Update your SMTP SECURE AND PORT TO:
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
That solved my issues with using Mandrill with SMTP.
I'm trying to make a forgot password system with PHPMailer on xampp.
But when I send an email,the email body is a html mail template,what I get from another file $mail->Body = file_get_contents('mail_template.php');,and I have problem,because I don't know how should I get the data of the $url variable and send it to mail_template.php file to use it for the link in the mail.
I tried the include 'filename.php'; command,but haven't worked.
Here is the code:
if (isset($_POST["submitButton"])) {
$emailTo = $_POST["email"];
$code = md5(uniqid(rand(), true));
$query = $con->prepare("INSERT INTO resetpasswords(code,email) VALUES('$code', '$emailTo')");
$query->execute();
if (!$query) {
exit("Something went wrong...");
}
$mail = new PHPMailer(true);
try {
//Server settings // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mail#gmail.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // 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('mail#mail.com', 'Email');
$mail->addAddress($emailTo); // Add a recipient
$mail->addReplyTo('no-reply#website.com', 'No reply');
// Content
$url = "http://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]) . "/resetPassword/code/$code";
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Reset your password!';
$mail->Body = file_get_contents('mail_template.php');
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
} catch (Exception $e) {
echo "Message could not be sent. Error: {$mail->ErrorInfo}";
}
header("refresh:10;url=login.php");
}
So from this php file,I want to send the data of the $url to the mail_template.php
Is this possible to do?
To send data to another url in php you have to try the following url:
`mail_template.php?data=mail#gmail.com`
then inside an empty mail_template.php do -
<?php
if (isset($_GET['data'])) {
$test = $_GET['data'];
//print the data added to the url
echo $test;
}
?>
I'm trying to send an email with the help of PHPMailer, everything works fine except now I want to have a copy of the send mail in Sent Items.
The website is currently hosted in Bluehost. I tried following the example of PHPMailer - GMail but I'm stuck on which path should I specify.
From the example of PHPMailer - GMail the path for Sent Items is:
{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail
I don't know what path should I specify. Everything works fine in my code, only the path for the sent item is missing.
<?php
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
$username = 'john#mydomain.com';
$password = 'password';
function save_mail( $mail ) {
//path or folder for sent items
$path = "{imap.mydomain.com:993/imap/ssl}[...]/..."; //what exactly is the path for my sent item.
//Tell your server to open an IMAP connection using the same username and password as you used for SMTP
$imapStream = imap_open( $path, $mail->Username, $mail->Password );
$result = imap_append( $imapStream, $path, $mail->getSentMIMEMessage() );
imap_close( $imapStream );
return $result;
}
function send(){
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->Host = 'mail.mydomain.com';
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
$mail->SMTPAuth = true;
$mail->Username = $username;
$mail->Password = $password;
$mail->setFrom( $username, 'John Doe' );
$mail->addAddress( 'someone#example.com', 'David Doe' );
$mail->Subject = 'TEST SUBJECT';
$mail->msgHTML('<b>TEST</b>');
$mail->AltBody = 'TEST';
if ( !$mail->send() ) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
if (save_mail($mail)) {
echo "Message saved!";
}
}
}
?>
Thanks to Max for the idea of imap_list function.
This gives me the list of a path for my mail directories.
$host = '{imap.mydomain.com/ssl/novalidate-cert}';
$mail = 'support#mydomain.com';
$pass = 'password';
$mbox = imap_open($host, $mail, $pass, OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$list = imap_list($mbox, $host, "*");
if (is_array($list)) {
foreach ($list as $val) {
echo imap_utf7_decode($val) . "\n";
}
} else {
echo "imap_list failed: " . imap_last_error() . "\n";
}
imap_close($mbox);
?>
using the {imap.mydomain.com} or {imap.mydomain.com:993/imap/ssl}gives me an error of:
can't connect: Certificate failure for imap.mydomain.com: Server
name does not match certificate: /OU=Domain Control
Validated/OU=Hosted by BlueHost.Com, INC/OU=PositiveSSL
Wildcard/CN=*.bluehost.com
Certificate issue, luckily I found this question and I end up using the following host:
{imap.mydomain.com/ssl/novalidate-cert}
and the path I'm looking to forward the sent mail into sent items is:
{imap.mydomain.com/ssl/novalidate-cert}INBOX.Sent
I'm trying to use PHPMailer to send e-mail from my local virtual host on XAMPP with the code below. I have enabled extension=php_openssl.dll in php.ini, still I get the error messages below. Anyone knows why?
require_once 'PHPMailerAutoload.php';
require_once 'class.phpmailer.php';
require_once 'class.smtp.php';
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Username = "xxx";
$mail->Password = "xxx";
$email = "xxx#gmail.com";
$name = "Test";
$email_from = "xxx#gmail.com";
$name_from = "Test";
$mail->AddAddress($email, $name);
$mail->SetFrom($email_from, $name_from);
$mail->Subject = "My Subject";
$mail->Body = "Mail contents";
try{
$mail->Send();
echo "Success!";
} catch(Exception $e){
echo "Fail - " . $mail->ErrorInfo;
}
Error output:
SMTP ERROR: Password command failed: 534-5.7.14
SMTP Error: Could not authenticate.
For those having issues with failing authentication using PHPMailer, and all settings and credentials are good, try using this:
$mail->AuthType = 'LOGIN';
in the PHP that is attempting to send the email.
I struggled for the longest, until I added this.
Cheers.
I am new to PHP. I was trying to send myself a sample e-mail through PHPmailer. I am using gmail's smtp server. I am trying to send a sample mail from my gmail account to my yahoo account. But I am getting the error : Mailer Error: SMTP connect() failed.
Here is the code :
<?php
require "class.phpmailer.php";
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->Host = "ssl://smtp.gmail.com";
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "myemail#gmail.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
$webmaster_email = "myemail#gmail.com"; //Reply to this email ID
$email="myyahoomail#yahoo.in"; // Recipients email ID
$name="My Name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->Port = 465;
$mail->FromName = "My Name";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"My Name");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
I am using WAMP server on a Windows 7 64-bit machine. What could be the prob?
Please help me solve this. Thanks!
The solution of this problem is really very simple. actually Google start using a new authorization mechanism for its User.. you might have seen another line in debug console prompting you to log into your account using any browser.! this is because of new XOAUTH2 authentication mechanism which google start using since 2014.
remember.. do not use the ssl over port 465, instead go for tls over 587. this is just because of XOAUTH2 authentication mechanism. if you use ssl over 465, your request will be bounced back.
what you really need to do is .. log into your google account and open up following address
https://www.google.com/settings/security/lesssecureapps
and check turn on . you have to do this for letting you to connect with the google SMTP because according to new authentication mechanism google bounce back all the requests from all those applications which does not follow any standard encryption technique.. after checking turn on.. you are good to go..
here is the code which worked fine for me..
require_once 'C:\xampp\htdocs\email\vendor\autoload.php';
define ('GUSER','youremail#gmail.com');
define ('GPWD','your password');
// make a separate file and include this file in that. call this function in that file.
function smtpmailer($to, $from, $from_name, $subject, $body) {
global $error;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->SMTPAutoTLS = false;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
$error = 'Message sent!';
return true;
}
}
You need to add the Host parameter
$mail->Host = "ssl://smtp.gmail.com";
Also, check if you have open_ssl enabled.
<?php
echo !extension_loaded('openssl')?"Not Available":"Available";
Solved an almost identical problem, by adding these lines to the standard PHPMailer configuration. Works like a charm.
$mail->SMTPKeepAlive = true;
$mail->Mailer = “smtp”; // don't change the quotes!
Came across this code (from Simon Chen) while researching a solution here, https://webolio.wordpress.com/2008/03/02/phpmailer-and-smtp-on-1and1-shared-hosting/#comment-89
Troubleshooting
You have add this code:
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
And Enabling Allow less secure apps:
"will usually solve the problem for PHPMailer, and it does not really make your app significantly less secure. Reportedly, changing this setting may take an hour or more to take effect, so don't expect an immediate fix"
This work for me!
$mail->SMTPKeepAlive = true;
$mail->isSendMail(); // instead of isSMTP();
On shared hosting, your mail server may occasionally experience connection issues.
Here I found solution
[Edit]
Here is the link content, in case the link stop working for some reason (it happens)
PHPMailer and SMTP on 1and1 shared hosting
I use PHPMailer on my 1and1 shared hosting account. Recently, I could not send email anymore.
I tried debugging and this is the error that PHPMailer throws:
Language string failed to load: connect_host
After googling for a solution and trying different SMTP servers, accounts and SMTP ports, I decided to switch to sendmail and it worked like a charm! All I needed to do was to replace $mail->isSmtp() with:
$mail->isSendMail()
sendMail is located in its default location on 1and1 servers : /usr/sbin/sendmail, so no change of settings was required.
Conclusion:
1and1 probably closed its outgoing SMTP ports on its shared hosting servers. Consequently, if you use PHPMailer, don’t use SMTP mode anymore.
If anyone is still unable to solve the issue, please check following thread and follow callmebob's answer.
PHPMailer - SMTP ERROR: Password command failed when send mail from my server
I fixed it ...
https://github.com/PHPMailer/PHPMailer/tree/5.2-stable
<?php
require '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 = 'm7#gmail.com'; // SMTP username
$mail->Password = 'pass'; // SMTP password
//$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25; // TCP port to connect to
$mail->setFrom('m7#gmail.com', 'Mailer');
$mail->addAddress('dot#gmail.com', 'User'); // Add a recipient
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</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;
} else {
echo 'Message has been sent';
}
Turn on access and enjoy..! That is on Gmail account setting.
You are missing the directive that states the connection uses SSL
require ("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true; // turn of SMTP authentication
$mail->Username = "YAHOO ACCOUNT"; // SMTP username
$mail->Password = "YAHOO ACCOUNT PASSWORD"; // SMTP password
$mail->SMTPSecure = "ssl";
$mail->Host = "YAHOO HOST"; // SMTP host
$mail->Port = 465;
Then add in the other parts
$webmaster_email = "myemail#gmail.com"; //Reply to this email ID
$email="myyahoomail#yahoo.in"; // Recipients email ID
$name="My Name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "My Name";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"My Name");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
As a side note, I have had trouble using Body + AltBody together although they are supposed to work. As a result, I wrote the following wrapper function which works perfectly.
<?php
require ("class.phpmailer.php");
// Setup Configuration for Mail Server Settings
$email['host'] = 'smtp.email.com';
$email['port'] = 366;
$email['user'] = 'from#email.com';
$email['pass'] = 'from password';
$email['from'] = 'From Name';
$email['reply'] = 'replyto#email.com';
$email['replyname'] = 'Reply To Name';
$addresses_to_mail_to = 'email1#email.com;email2#email.com';
$email_subject = 'My Subject';
$email_body = '<html>Code Here</html>';
$who_is_receiving_name = 'John Smith';
$result = sendmail(
$email_body,
$email_subject,
$addresses_to_mail_to,
$who_is_receiving_name
);
var_export($result);
function sendmail($body, $subject, $to, $name, $attach = "") {
global $email;
$return = false;
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = $email['host']; // SMTP server
// $mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = $email['host']; // sets the SMTP server
$mail->Port = $email['port']; // set the SMTP port for the GMAIL server
$mail->SMTPSecure = "tls";
$mail->Username = $email['user']; // SMTP account username
$mail->Password = $email['pass']; // SMTP account password
$mail->AddReplyTo($email['reply'], $email['replyname']);
if(stristr($to,';')) {
$totmp = explode(';',$to);
foreach($totmp as $destto) {
if(trim($destto) != "") {
$mail->AddAddress(trim($destto), $name);
}
}
} else {
$mail->AddAddress($to, $name);
}
$mail->SetFrom($email['user'], $email['from']);
$mail->Subject = $subject;
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($body);
if(is_array($attach)) {
foreach($attach as $attach_f) {
if($attach_f != "") {
$mail->AddAttachment($attach_f); // attachment
}
}
} else {
if($attach != "") {
$mail->AddAttachment($attach); // attachment
}
}
$mail->Send();
} catch (phpmailerException $e) {
$return = $e->errorMessage();
} catch (Exception $e) {
$return = $e->errorMessage();
}
return $return;
}
if everything fails then for gmail you must turn on access to 3rd party apps to connect to ur gmail account.
https://www.google.com/settings/security/lesssecureapps // turn it
on
Just make sure you passed the right parameters
eg. the correct outgoing server host, username, and password
$mail->SMTPDebug = false;
$mail->Host = 'email_smtp_host'
$mail->SMTPAuth = false
$mail->Username = 'username'
$mail->Password = 'password'
$mail->SMTPSecure 'tls'
$mail->Port = '587'
If you're using VPS and with httpd service, please check if your httpd_can_sendmail is on.
getsebool -a | grep mail
to set on
setsebool -P httpd_can_sendmail on
Try adding this line to your script. This worked for me!
$mail->Mailer = “smtp”;
This is usually a result of the server not accepting SSLv2 or SSLv3 connections which is a standard for cPanel/WHM in favor of TLS only connections. You can check this by going to WHM>>Service Configuration>>Exim Configuration Manager -> Options for OpenSSL
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
<?php
use PHPMailer\PHPMailer\PHPMailer;
require_once "PHPMailer/src/Exception.php";
require_once "PHPMailer/src/PHPMailer.php";
require_once "PHPMailer/src/SMTP.php";
$mail = new PHPMailer();
$mail ->isSMTP();
$mail ->Host ="smtp.gmail.com";
$mail -> SMTPAuth = true;
$mail ->Username = 'youremail#gmail.com';
$mail ->Password = 'password';
//$mail ->SMTPSecure=PHPMailer::ENCRYPTION_STARTTLS;
$mail ->Port = '587';
$mail ->SMTPSecure ='tls';
$mail ->isHTML(true);
$mail ->setFrom('youremail#gmail.com','email send name');
$mail ->addAddress('receiver#gmail.com');
$mail ->Subject = 'HelloWorld';
$mail ->Body = 'a test email';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
if ($mail->send()){
echo "Message has been sent successfully";
}else{
echo "Mailer Error: " . $mail->ErrorInfo;
}
?>
make sure that you configure less secure app settings in gmail using this link https://www.google.com/settings/security/lesssecureapps and make sure you downloaded PHPMailer-master.zip from github
working fine with MAMP server locally :)
After days of searching, I found out that the protocol name needs to be in lowercase.
$mail->SMTPSecure = "ssl"; # lowercase
find the "class.smtp.php" file
original:
$this->smtp_conn =fsockopen(
$host,
$port,
$errno,
$errstr,
$timeout
);
change to:
$this->smtp_conn = #stream_socket_client(
$host,
$port,
$errno,
$errstr,
$timeout
);