This question already has answers here:
SMTP connect() failed phpmailer
(1 answer)
SMTP connect() failed PHPmailer - PHP
(17 answers)
Closed 1 year ago.
I'm using 000webhost server and I got an error while sending the email using PHPMailer, knowing that it works in localhost with tls and Port 587
Here is my code
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require $_SERVER['DOCUMENT_ROOT'] . '/Portfolio/mail/Exception.php';
require $_SERVER['DOCUMENT_ROOT'] . '/Portfolio/mail/PHPMailer.php';
require $_SERVER['DOCUMENT_ROOT'] . '/Portfolio/mail/SMTP.php';
if(isset($_POST['hdn-insert'])) {
$data=array();
$variables = array();
$name = $_POST['name'];
$email_from = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$query = #unserialize (file_get_contents('http://ip-api.com/php/'));
$location = $query['city'] . ', ' . $query['country'] . '.';
$year = date('Y');
$variables['name'] = $_POST['name'];
$variables['email'] = $_POST['email'];
$variables['message'] = $_POST['message'];
$variables['location'] = $location;
$variables['year'] = $year;
$template = file_get_contents('MailUI.html');
foreach($variables as $key => $value)
{
$template = str_replace('{{ '.$key.' }}', $value, $template);
}
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
$mail->Host = "smtp.gmail.com"; // use $mail->Host = gethostbyname('smtp.gmail.com'); // if your network does not support SMTP over IPv6
$mail->Port = 587; // TLS only
$mail->SMTPSecure = 'tls'; // ssl is deprecated
$mail->SMTPAuth = true;
$mail->Username = 'hazemcrunchy#gmail.com'; // email
$mail->Password = '**********'; // password
$mail->setFrom($email_from, $name); // From email and name
$mail->addAddress('hazemsamiir196#gmail.com', 'Hazem El-behairy'); // to email and name
$mail->Subject = $subject;
$mail->msgHTML($template); //$mail->msgHTML(file_get_contents('contents.html'), __DIR__); //Read an HTML message body from an external file, convert referenced images to embedded,
$mail->AltBody = 'HTML messaging not supported'; // If html emails is not supported by the receiver, show this body
// $mail->addAttachment('images/phpmailer_mini.png'); //Attach an image file
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
if(!empty($name) && !empty($email_from) && !empty($subject) && !empty($message) && strlen($message) >= '8'){
if(!ctype_space($name) && !ctype_space($email_from) && !ctype_space($subject) && !ctype_space($message)){
if ($mail->send()){
$data['status'] = 1;
} else {
$data['status'] = 0;
}
echo json_encode($data);
} else {
$data['status'] = 0;
}
}
else{
$data['status'] = 0;
}
}
?>
The error message is:
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
I hope you guys get me well.
Related
I am attempting to send over 1,000 emails through phpmailer, however after roughly the 100 email sent, it stops sending them, do you know why this could be? Here is my code.
I am using PHPmailer and Google SMTP, with a g suite email as the sender.
It does execute every function perfectly, but for some reason it just randomly stops in the loop. Very lost.
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
header('Content-Type: application/json');
require '/var/www/fakewebsite.com/vendor/autoload.php';
$newsletterid = $_POST['newsletterid'];
$allcontacts = Contacts::ReadAllNewsletter();
$allnewseletters = Newsletter::ReadAllNewsletter();
$mail = new PHPMailer(true);
//Server settings
//Enable verbose debug output
$mail->isSMTP();
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->SMTPKeepAlive = true; //Keep SMTP Connection Alive During Loop
$mail->Host = 'smtp.gmail.com'; //Set the SMTP server to send through
$mail->Username = 'test#example.com'; //SMTP usernames
$mail->Password = 'fakepassword'; //SMTP password
$mail->SMTPSecure = 'tls'; //Enable implicit TLS encryption
$mail->Port = 587;
$mail->SMTPDebug = 1;
$mail->addReplyTo('test#example.com', 'Fake Name');
foreach ($allcontacts as $eachcontact) {
foreach ($allnewseletters as $eachnewsletter) {
if ($eachnewsletter["id"] == $newsletterid) {
if ($eachnewsletter["contactlist"] == 1) {
if ($eachcontact["contacttype"] == 'Client') {
if ($eachcontact["subscribed"] == 1) {
$sendnewsletter = new Newsletter();
$sendnewsletter->contactid = $eachcontact["id"];
$sendnewsletter->newsletterid = $eachnewsletter["id"];
$newslettercounter = new Newsletter();
$newslettercounter->id = $eachnewsletter["id"];
//Recipients
$mail->setFrom('fakewebsite#example.com', $eachnewsletter["fromname"]);
$mail->addAddress($eachcontact["email"]);
$message1 = file_get_contents('/var/www/fakewebsite.com/public_html/admin/emailtemplates/newsletterunfilled.php');
$message1 = str_replace('{NEWSLETTERCONTENT}', $eachnewsletter["content"], $message1);
$message1 = str_replace('{First Name}', $eachcontact["name"], $message1);
$message1 = str_replace('..', "https://fakewebsite.com/admin", $message1);
$message1 = str_replace("api/unsubscribe.php?contactid={contactid}&newsletterid={newsletterid}", "https://fakewebsite.com/admin/newsletter/api/unsubscribe.php?contactid={contactid}&newsletterid={newsletterid}", $message1);
$message1 = str_replace('<span style="color: #ffffff;"><a style="color: #ffffff;" href="https://www.divinestatus.com" target="_blank" rel="noopener"><strong>SCHEDULE TRANPORT</strong></a></span>', '<span style="color: #ffffff;"><a style="color: #ffffff;" href="https://fakewebsite.com/admin/newsletter/api/linkclicked.php?url=https://www.fakewebsite.com&contactid={contactid}&newsletterid={newsletterid}" target="_blank" rel="noopener"><strong>SCHEDULE TRANPORT</strong></a></span>', $message1);
$message1 = str_replace('{First Name}', $eachcontact["name"], $message1);
$message1 = str_replace('{contactid}', $eachcontact["id"], $message1);
$message1 = str_replace('{newsletterid}', $eachnewsletter["id"], $message1);
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = $eachnewsletter["subject"];
$mail->Body = $message1;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$sendnewsletter->delivered = 1;
$sendnewsletter->SendNewsletter();
$newslettercounter->NewsletterDelivered();
$result = array('status' => "success", 'message' => "Message sent.");
echo json_encode($result);
if (!$mail->send()) {
$result = array('status' => "error", 'message' => "Message not sent!.");
echo json_encode($result);
echo "Mail Not Sent";
$sendnewsletter->delivered = 0;
$sendnewsletter->SendNewsletter();
}
$mail->ClearAllRecipients();
sleep(1);
}
}
}
}
}
}
I am trying to send email with multiple attachments using PHPMailer class. Multiple files are uploading successfully in directory but it's sending just one file in Email. And how to format my email body using bootstrap? Your suggestions will be highly appreciated. I am using PHPMailer 6.0.5
Here is my PHP Code:
<?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'])) {
$inputZip = $_POST['inputZip'];
$selectService = $_POST['selectService'];
$lawnMovingService = $_POST['lawnMovingService'];
$leafRemovalService = $_POST['leafRemovalService'];
$snowPlowingService = $_POST['snowPlowingService'];
$handymanService = $_POST['handymanService'];
$inputName = $_POST['inputName'];
$inputEmail = $_POST['inputEmail'];
$inputPhone = $_POST['inputPhone'];
$inputMessage = $_POST['inputMessage'];
if (isset($_FILES['images']['name']) && $_FILES['images']['name'] != '') {
$destination = "attachment/";
foreach ($_FILES["images"]["tmp_name"] as $key => $value) {
$tmp_name = $_FILES["images"]["tmp_name"][$key];
$name = $destination . basename($_FILES["images"]["name"][$key]);
move_uploaded_file($tmp_name, $name);
}
} else {
$name = '';
}
$mail = new PHPMailer;
//For SMTP
//$mail->Host = "smtp.gmail.com";
//$mail->isSMTP(); // This line may cause problem
//$mail->SMTPAuth = true;
//$mail->Username = "example#gmail.com";
//$mail->Password = "examplePassword";
//$mail->SMTPSecure = "ssl"; //OR TLS
//$mail->Port = 465; //TLS : 587
$mail->addAddress('milan.uptech#gmail.com');
$mail->setFrom($inputEmail);
$mail->Subject = 'Service Booking from Website';
$mail->isHTML(true);
$mail->Body = $inputMessage;
$mail->addAttachment($name);
if ($mail->send()) {
header('Location: index.php');
} else {
header('Location: contact.php');
}
// if(sendemail('milan.uptech#gmail.com', $email, $name, $body, $file)) {
// $msg = 'Email Sent!';
// sendemail($inputEmail, 'milan.uptech#gmail.com', $inputName, 'We have received your email');
// }
}
I moved the class creation up to be before the file file processing loop, and moved the attachment code in to the loop
<?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'])) {
$inputZip = $_POST['inputZip'];
$selectService = $_POST['selectService'];
$lawnMovingService = $_POST['lawnMovingService'];
$leafRemovalService = $_POST['leafRemovalService'];
$snowPlowingService = $_POST['snowPlowingService'];
$handymanService = $_POST['handymanService'];
$inputName = $_POST['inputName'];
$inputEmail = $_POST['inputEmail'];
$inputPhone = $_POST['inputPhone'];
$inputMessage = $_POST['inputMessage'];
$mail = new PHPMailer; //moved here
if (isset($_FILES['images']['name']) && $_FILES['images']['name'] != '') {
$destination = "attachment/";
foreach ($_FILES["images"]["tmp_name"] as $key => $value) {
$tmp_name = $_FILES["images"]["tmp_name"][$key];
$name = $destination . basename($_FILES["images"]["name"][$key]);
move_uploaded_file($tmp_name, $name);
$mail->addAttachment($name); //attache here
}
} else {
$name = '';
}
//For SMTP
//$mail->Host = "smtp.gmail.com";
//$mail->isSMTP(); // This line may cause problem
//$mail->SMTPAuth = true;
//$mail->Username = "example#gmail.com";
//$mail->Password = "examplePassword";
//$mail->SMTPSecure = "ssl"; //OR TLS
//$mail->Port = 465; //TLS : 587
$mail->addAddress('milan.uptech#gmail.com');
$mail->setFrom($inputEmail);
$mail->Subject = 'Service Booking from Website';
$mail->isHTML(true);
$mail->Body = $inputMessage;
if ($mail->send()) {
header('Location: index.php');
} else {
header('Location: contact.php');
}
// if(sendemail('milan.uptech#gmail.com', $email, $name, $body, $file)) {
// $msg = 'Email Sent!';
// sendemail($inputEmail, 'milan.uptech#gmail.com', $inputName, 'We have received your email');
// }
}
So i have the following code:
while(list($i, $data_subscriber) = each($subscriber)) {
$email_counter = $i + 1;
echo ($email_counter).') '.$data_subscriber->field_1.' '.$data_subscriber->field_2.' - '.$data_subscriber->email.''."\n";
flush();
$language = $data_subscriber->lang;
$body_mail = include($template_send_newsletter);
$first_name_idx = $data_subscriber->field_1;
$last_name_idx = $data_subscriber->field_2;
if (mail_send(strtolower($data_subscriber->email),
( IsSet($first_name_idx) && IsSet($last_name_idx) ? $first_name_idx.' '.$last_name_idx : $data_subscriber->email ),
$site_admin,
$site_name,
'Newsletter ['.date('d/m/Y', time()).']',
true,
$body_mail,
NULL,
false)) {
reset($data_subscriber->newsletter_item);
unset($log_detail);
$log_detail = "";
while(list($j, $list_of_news_to_send) = each($data_subscriber->newsletter_item)) {
$log_detail = ( IsSet($list_of_news_to_send->title) ? $list_of_news_to_send->title."\n" : '');
$log_detail = ( IsSet($list_of_news_to_send->subtitle) ? $list_of_news_to_send->subtitle."\n" : '');
$log_detail = ( IsSet($list_of_news_to_send->creation_date) ? $list_of_news_to_send->creation_date."\n" : '');
$log_detail = "\n";
} /* end while */
write_newsletter_detail($data_subscriber->id_subscription,
$data_subscriber->email,
'Y',
$log_detail);
}
else {
write_newsletter_detail($data_subscriber->id_subscription,
$data_subscriber->email,
'N',
NULL);
} /* end if mail_send */
} /* end while */
And the following function
function mail_send($rcpt_to,
$to_name,
$mail_from,
$from_name,
$subject,
$isHTML = true,
$body,
$attachment = NULL,
$direct_delivery = false,
$reply_to = NULL){
$mail = new PHPmailer;
$mail->isSMTP();
$mail->SMTPDebug = 3;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "mail#domain.com";
$mail->Password = "password";
$mail->Timeout = 3600;
$mail->addAddress(trim($rcpt_to), trim($to_name));
$mail->setFrom($mail_from,$from_name);
$mail->Subject = $subject;
$mail->Body = $body;
if ($isHTML) {
$mail->IsHTML(true);
$mail->AltBody = strip_tags($mail->Body);
}
if (IsSet($attachment)) {
$mail->AddAttachment($attachment['tmp_name'], $attachment['name']);
}
if (IsSet($reply_to)) {
$mail->AddReplyTo($reply_to);
}
if (!$mail->send()) {
return false;
} else {
return true;
}
}
I am using PHPMailer to send multiple e-mails using gmail SMTP server.
I have 4 files containing different but almost the same code to send newsletter.
One of my files is sending all the emails to ( ~60 recipients )
The other 3 files, each of them needs to send one email to ~600 recipients.
Problem occures here, half of the e-mails are sent the other are not.
If I run the script but this time for fewer recipients witch didn't recieved the e-mail first time, it's sending.
I'm using GMAIL with my own domain. So i'm not exceeding any limit.
What may cause this problem ? Any ideas ? Thank you.
UPDATE**
SERVER -> CLIENT: 454 4.7.0 Too many login attempts, please try again later. e11sm950198edd.68 - gsmtp
After some emails that are sent i recieve this error. Any ideas why ?
UPDATE***
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 3;
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
$mail->Username = "domain#domain.com";
$mail->Password = "password";
$mail->setFrom($site_noreply, $site_name);
$subjectnewsletter = 'Newsletter ['.date('d/m/Y', time()).']';
$mail->Subject = $subjectnewsletter;
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
reset($subscriber);
while(list($i, $data_subscriber) = each($subscriber)) {
$email_counter = $i + 1;
echo ($email_counter).') '.$data_subscriber->field_1.' '.$data_subscriber->field_2.' - '.$data_subscriber->email.''."\n";
flush();
$language = $data_subscriber->lang;
$first_name_idx = $data_subscriber->field_1;
$last_name_idx = $data_subscriber->field_2;
$fullname = $first_name_idx.' '.$last_name_idx;
$bodymail = include($template_send_newsletter);
$mail->msgHTML($bodymail);
$mail->addAddress($data_subscriber->email, $fullname);
reset($data_subscriber->newsletter_item);
unset($log_detail);
$log_detail = "";
while(list($j, $list_of_news_to_send) = each($data_subscriber->newsletter_item)) {
$log_detail = ( IsSet($list_of_news_to_send->title) ? $list_of_news_to_send->title."\n" : '');
$log_detail = ( IsSet($list_of_news_to_send->subtitle) ? $list_of_news_to_send->subtitle."\n" : '');
$log_detail = ( IsSet($list_of_news_to_send->creation_date) ? $list_of_news_to_send->creation_date."\n" : '');
$log_detail = "\n";
} /* end while */
if (!$mail->send()) {
write_newsletter_detail($data_subscriber->id_subscription,
$data_subscriber->email,
'N',
NULL);
echo $mail->ErrorInfo;
break; //Abandon sending
} else {
write_newsletter_detail($data_subscriber->id_subscription,
$data_subscriber->email,
'Y',
$log_detail);
echo "Message sent";
}
$mail->clearAddresses();
$mail->clearAttachments();
} /* end while */
I managed to change my code so it's not connect to the smtp server every e-mail.
But now after it sends 93 emails i get the follosing error:
SMTP server error: MAIL FROM command failed
You need to use an MTA that uses more than one connection and it already setup to respect limits of the servers you're connecting to. At this point you're attempting to exceed the limits of the server you're connecting to and companies like Google frown on too many connections or using their mail servers for broadcasts.
Look for a mail sending service if your numbers are modest, or consider purchasing and hosting an MTA if you send a considerable amount of email.
You can use SMTP relay configuration which allow you to send email from your server with any of your email domain address.
I have some troubles with my sending loop with PHP Mailer:
<?php
foreach ($packTabCible as $key => $pack) {
// PHPMailer
$mail = new PHPMailer;
$mail->Mailer = "smtp";
$mail->isSMTP();
$mail->SMTPKeepAlive = true;
$mail->SMTPAuth = true;
$mail->Encoding = '8bit';
$mail->SMTPDebug = 3;
$mail->setLanguage('fr', './PHPMailer/language/');
$mail->CharSet = 'UTF-8';
$mail->WordWrap = 10000;
$mail->Host = $hostname;
$mail->Username = $username;
$mail->Password = $pass;
$mail->SMTPSecure = $tls;
$mail->Port = $port;
$mail->FromName = utf8_decode($from_name);
$mail->isHTML(true);
$mail->Subject = utf8_decode($sujet);
$mail->From = $from_mail;
foreach ($pack as $email => $md5) {
$mail->addAddress($email);
$header = str_replace("#miroir#", $link_miroir, $ip_header_html);
$footer = str_replace("#lien#", $link_unsub, $ip_footer_html);
$content = str_replace("<body>", "<body>".$header, $message);
$content = str_replace("</body>", $footer.'</body>', $content);
$content = str_replace("#email#", $email, $content);
$mail->Body = $content;
$mail->AltBody = str_replace("#miroir#", $link_miroir, utf8_decode($ip_header_txt))
. $txt
. str_replace("#lien#", $link_unsub, $ip_footer_txt);
$mail->send();
$mail->clearAddresses();
usleep($timer);
}
$mail->SmtpClose();
usleep(5000000);
}
?>
I'm 100% sure of the validity of the parameters I send to PHPMailer.
There is 2 loops, and I reset the connexion after each loop of $packTabCible with $mail->SmtpClose();
But, PHPMailer return the error:
The following From address failed: news#my-domain.com : MAIL FROM command failed,0 ok
,
2,SMTP server error: MAIL FROM command failed Detail: 0 ok
SMTP code:
2SMTP server error: MAIL FROM command failed Detail: 0 ok
SMTP code:
2
But news#my-domain.com is the good one so the problem is elsewhere...
If someone have an idea, big thanks
I am having problem with sending mail using phpmailer. I am a beginner programmer. I am trying to make contact form. My code is as follow(submit.php). Please suggest me.. Thanks in advance .
session_start();
require_once 'libs/phpmail/PHPMailerAutoload.php';
$errors = array();
if(isset($_POST['name'], $_POST['phone'],$_POST['mail'],$_POST['message'])){
$fields = array(
'name' => $_POST['name'],
'phone' => $_POST['phone'],
'email' => $_POST['mail'],
'message' => $_POST['message']
);
foreach ($fields as $field => $data) {
if(empty($data)){
$errors[] = 'The '. $field . ' field is required';
}
}
if(empty($errors)){
$m = new PHPMailer;
$m -> isSMTP();
$m -> SMTPAuth = true;
//$m -> SMTPDebug = 2;
$m -> Host = 'smtp.gmail.com';
$m -> Username = 'xxxx#gmail.com';
$m -> Password = 'xxxx';
$m -> SMTPSecure = 'ssl';
$m -> Port = 465;
$m -> isHTML();
$m -> Subject = 'Contact form submitted';
$m -> Body = 'From: ' . $fields['name']. '('. $fields['phone'] . $fields['email']. ')'.'<p>' .$fields['message'] .'</p> ';
$m -> FromName = 'Contact';
// $m ->addReplyTo($fields['email'], $fields['name']);
$m -> addAddress('ssss#gmail.com', 'xxxxxxxx');
if($m->send()){
header('Location: thanks.php');
die();
}else{
$errors[] = 'Sorry could not send email. Please try again';
}
}
}else{
$errors[] = 'some thing went wrong';
}
$_SESSION['error'] = $errors;
$_SESSION['field'] = $fields;
header('Location: form.php');
My setting phpmailer, everything works
function __construct ($to, $subject, $body) {
date_default_timezone_set('Etc/UTC');
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
$mail->CharSet = 'UTF-8';
//Set the hostname of the mail server
$mail->Host = "mail.xxxxxx.com";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
$mail->AuthType = 'PLAIN';
//Username to use for SMTP authentication
$mail->Username = "xxxx";
//Password to use for SMTP authentication
$mail->Password = "xxxx";
//Set who the message is to be sent from
$mail->setFrom('erp#xxxxxx.com');
//Set an alternative reply-to address
//$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress($to);
//Set the subject line
$mail->Subject = $subject;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML($body);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
$this->mail = $mail;
}
function SendMail () {
//send the message, check for errors
if (!$this->mail->send()) {
return "Mailer Error: " . $this->mail->ErrorInfo;
} else {
return true;
}
}
// using
$email = $this->request->getPost('email');
$smtp = new \SmtpClient($email, 'Test', $template);
$result = $smtp->SendMail();
Remove
$m -> Subject = 'Contact form submitted';
And try again.
When I remove the subject it worked.