Response - SMTP mailer - phpMailer - smtp

I am using phpMailer for sending bulk email, Some of emails are bouncing, How I get Hard Bounced email ids.
I am new in PHP, I found in some websites i will get responses like
500 - The server could not recognize the command due to a syntax error.
501 - A syntax error was encountered in command arguments.
502 - This command is not implemented.
503 - The server has encountered a bad sequence of commands.
504 - A command parameter is not implemented.
550 - The requested command failed because the user's mailbox was unavailable (for example because it was not found, or because the command was rejected for policy reasons).
551 - The recipient is not local to the server. The server then gives a forward address to try.
552 - The action was aborted due to exceeded storage allocation.
553 - The command was aborted because the mailbox name is invalid.
554 - The transaction failed. Blame it on the weather.
but I didnt fount any where how I get this response?

When you run "Send()" method you may check "ErrorInfo" property:
$mail = new PHPMailer();
...
if(!$mail->Send())
{
echo "Message could not be sent.";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
or
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
...
try
{
...
$mail->Send();
}
catch (phpmailerException $e)
{
echo $e->errorMessage(); // Error messages from PHPMailer
}
catch (Exception $e)
{
echo $e->getMessage(); // Something else
}

Related

SMTP error when using $_ENV for credentials in PHPMailer

When using hard-coded username / email / password I have no problem getting a message sent with phpmailer. But when I use $_ENV to hide the credentials I get the smtp error as shown here:
2020-09-08 15:50:51 SERVER -> CLIENT: 220 dd45234.kasserver.com ESMTP
2020-09-08 15:50:51 CLIENT -> SERVER: EHLO browsegenres-f3.loc
2020-09-08 15:50:51 SERVER -> CLIENT: 250-dd45234.kasserver.com250-PIPELINING250-SIZE 102400000250-VRFY250-ETRN250-STARTTLS250-AUTH PLAIN LOGIN250-AUTH=PLAIN LOGIN250-ENHANCEDSTATUSCODES250-8BITMIME250 DSN
2020-09-08 15:50:51 CLIENT -> SERVER: STARTTLS
2020-09-08 15:50:51 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2020-09-08 15:50:51 CLIENT -> SERVER: EHLO xxxxxxxxxxxxxxxxxxxx.loc
2020-09-08 15:50:51 SERVER -> CLIENT: 250-xxxxxxxx.[SERVER].com250-PIPELINING250-SIZE 102400000250-VRFY250-ETRN250-AUTH PLAIN LOGIN250-AUTH=PLAIN LOGIN250-ENHANCEDSTATUSCODES250-8BITMIME250 DSN
2020-09-08 15:50:51 CLIENT -> SERVER: AUTH LOGIN
2020-09-08 15:50:51 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2020-09-08 15:50:51 CLIENT -> SERVER: [credentials hidden]
2020-09-08 15:50:53 SERVER -> CLIENT: 535 5.7.8 Error: authentication failed: VXNlcm5hbWU6
2020-09-08 15:50:53 SMTP ERROR: Username command failed: 535 5.7.8 Error: authentication failed: VXNlcm5hbWU6
SMTP Error: Could not authenticate.
2020-09-08 15:50:53 CLIENT -> SERVER: QUIT
2020-09-08 15:50:53 SERVER -> CLIENT: 221 2.0.0 Bye
SMTP Error: Could not authenticate.
Message could not be sent. Mailer Error: SMTP Error: Could not authenticate.
I don't wan to hardcode the credentials. Any idea how to get rid of this error?
Here's the code:
// initiate phpMailer
$mail = new PHPMailer(true);
// see config file
$mailSenderName = $_ENV['MAILER_CONTACT_USERNAME'];
$masterPassword = $_ENV['MAILER_CONTACT_PASSWORD'];
$masterEmail = $_ENV['MAILER_CONTACT_EMAIL'];
$recipient = $_ENV['MAILER_CONTACT_RECIPIENT'];
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'xxxxxxx.[SERVER].com';
$mail->SMTPAuth = true;
$mail->Username = $masterEmail;
$mail->Password = $masterPassword;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 25;
//Recipients
$mail->setFrom('aaa#bbbbbbbbbbb.com', 'aabbcc');
$mail->addAddress('mmmmmmmmm#bbbbbbbbbbb.com');
// Content
$mail->isHTML(true);
$mail->Subject = 'Message Received (Contact Page)';
$emailbody =
'There is a new message from: <br>' .
'==================================== <br>' .
$senderName . '<br>' .
$senderEmail . '<br' .
'====================================' .
$message . '<br>' .
'====================================';
$mail->Body = $emailbody;
$mail->send();
// success, show thank you
$f3->reroute('/contact/thankyou'); //todo
} catch (\Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Thanks!
Debug one thing at a time. There's no point in looking at error in your email when you know you know you have a problem before it ever gets that far. PHPMailer uses whatever you give it, so you need to be sure you're giving it the right thing.
You could reduce the code to debug in this case by cutting it back to:
var_dump($_ENV);
Once you know that you're setting the contents of $_ENV correctly (whether from real env vars, from a dotenv script, your php.ini config, etc), you can then start using the values in your email code.
After installing dotenv (vlucas) I simply didn't include it correctly in my ContactController. So that's why var_dump($_ENV) always resulted in NULL. I compared my settings with the other route, NewsletterController. The difference is that in this route I query the database and in the models constructor (where the db connection is set) I 'use' the dotenv class correctly, and that's why the $_ENV is filled with data. I simply didn't see it.
So, in ContactController I set:
use \Dotenv;
and after initialising phpmailer I added:
$mail = new PHPMailer(true);
$dotenv = Dotenv\Dotenv::createImmutable($_SERVER['DOCUMENT_ROOT']);
$dotenv->load();
Difference to Models class (database connection):
namespace Models;
use \Dotenv;
abstract class Model
{
protected $db;
public function __construct()
{
$dotenv = Dotenv\Dotenv::createImmutable($_SERVER['DOCUMENT_ROOT']);
$dotenv->load();
$this->db = new \DB\SQL(
'mysql:host='. $_ENV['DB_HOST'] .';port='.$_ENV['DB_PORT'].';dbname='.$_ENV['DB_NAME'],
$_ENV['DB_USERNAME'],
$_ENV['DB_PASSWORD']
);
}
}

cURL error: Failed to connect to xxxxxx(bucketname) port 80: Connection timed out (7)

I am uploading a file to Alibaba Cloud - OSS bucket. Have correct access key and secret key.
Using oss-sdk-php through yii2, Getting Error
{"name":"PHP Fatal Error","message":"Uncaught exception
'OSS\Core\OssException' with message 'RequestCoreException: cURL
resource: Resource id #351; cURL error: Failed to connect to
chinaproduct.oss-cn-beijing.aliyuncs.com port 80: Connection timed out
(7)'
Unable to get exact issue, any help would be appreciated.
// #### Delete old files / Fetch all files with prefix
$listObjectInfo = $ossClient->listObjects($productBucket,array('prefix'=>$uploadProductPrefix));
$objectList = $listObjectInfo->getObjectList();
foreach ($objectList as $objectInfo) {
$fileNameToDelete = $objectInfo->getKey();
$ossClient->deleteObject($productBucket,$fileNameToDelete);
\Yii::info("OSS : Deleted file from OSS -$productBucket - $fileNameToDelete");
}
} catch (OssException $e) {
\Yii::info("OSS : Unable to delete old files from OSS $productBucket for dataId $dataId " . $e);
}

Symfony No Route To Host on edit, but works fine on findAll

I am using Symfony 3.0.4. I have the error
[2016-05-20 08:50:26] request.CRITICAL: Uncaught PHP Exception Doctrine\DBAL\Exception\ConnectionException: "An exception occured in driver: SQLSTATE[HY000] [2002] No route to host" at /var/www/WebProduction/products.markettraders.com/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php line 103 {"exception":"[object] (Doctrine\\DBAL\\Exception\\ConnectionException(code: 0): An exception occured in driver: SQLSTATE[HY000] [2002] No route to host at /var/www/WebProduction/products.markettraders.com/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:103, Doctrine\\DBAL\\Driver\\PDOException(code: 2002): SQLSTATE[HY000] [2002] No route to host at /var/www/WebProduction/products.markettraders.com/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:47, PDOException(code: 2002): SQLSTATE[HY000] [2002] No route to host at /var/www/WebProduction/products.markettraders.com/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:43)"} []
[2016-05-20 08:50:26] security.DEBUG: Stored the security token in the session. {"key":"_security_main"} []
This is strange because the indexAction is working perfectly, only the Edit Action is NOTWorking, on all of my edit routes. There have been no changes in the code to cause this to happen.
What have I inadvertantly changed in my MySQL configuration that allows Doctrine to find everything on the indexAction but then error out on the editAction?
EDIT
Forgive me.... The code is below. It works in my local environment. It does not work in prod. The error above comes from the prod.log.
In addition the indexAction controller works as well.
/**
* Displays a form to edit an existing AOD Technical Analysis page entity.
*
* #Route("/{id}/edit", name="aod_technical_analysis_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, AodTechnicalAnalysis $aod_tech)
{
$deleteForm = $this->createDeleteForm($aod_tech);
$editForm = $this->createForm('AppBundle\Form\AodTechnicalAnalysisType', $aod_tech);
$editForm->remove('currencypair');
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($aod_tech);
$em->flush();
$session = $request->getSession();
$message = 'The change was succesfully saved for ' . $aod_tech->getCurrencypair();
$session->getFlashBag()->add('success', $message);
return $this->redirectToRoute('aod_technical_analysis_index');
}
return $this->render('aod_tech/edit.html.twig', array(
'aod_tech' => $aod_tech,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
Have you tried appending "app_dev.php" on your URL to get the debug web toolbar? I have found this to be more helpful compared to logs. You might need to edit the "web/app_dev.php" to add your browser's IP address.

Postfix Mail Server on Webmin. Failed to connect to server, permission denied(13)

I used PHPMailer to send out email and it work perfectly fine on localhost. However, as client requested, we have to upload everything onto webmin. The PostFix Mail Server was being installed for us. The problem is that I could not get the email function to work on the server.
Here are my codes.
<?php
require_once('class.phpmailer.php');
$mail = new PHPMailer();
$body = 'Test Email';
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "smtp.xxx.xxx.xx";
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "";
$mail->Password = "";
$mail->SMTPSecure = 'tsl';
$mail->SetFrom('support#xxx.xxx', 'Support');
$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);
$address = "xxx#hotmail.com";
$mail->AddAddress($address, "Sara Chan");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
Error message:
SMTP ERROR: Failed to connect to server: Permission denied (13) SMTP connect() failed. Mailer Error: SMTP connect() failed.
I have tried configuring the postfix main.cf file, but it still does not work.
I've tried:
http://postfix.state-of-mind.de/patrick.koetter/smtpauth/postfix_configuration.html
http://www.postfix.org/BASIC_CONFIGURATION_README.html
http://wiki.centos.org/HowTos/postfix
http://www.postfix.org/STANDARD_CONFIGURATION_README.html#null_client
Configuration from these links are different. I'm a new PHP programmer (Still an undergraduate student), and all these are really confusing. Right now, my postfix main.cf is back to its 'default' state. What should I do now?
It looks like you're using an old version of PHPMailer, so update that.
If you're sending from the same server as your script (which it sounds like you are since you're configuring postfix), don't use SMTP, call the IsMail() or IsSendmail() function instead of IsSMTP().
There's no such SMTP secure mode as 'tsl' - you're thinking of 'tls', and if you were going to use that it would probably be on port 587 rather than 25.
You won't need to supply auth credentials if you're sending via mail or sendmail.
I had the same error on a Oracle Linux 7.7 server and solved it by entering the following commands:
sudo setsebool -P httpd_can_sendmail 1
sudo setsebool -P httpd_can_network_connect 1

Twitter data content JSON parsing Issue

i have a script which i took from this link
http://tareq.wedevs.com/2009/05/playing-with-twitter-json-using-php/
the script is below
<?php
$json = file_get_contents("http://twitter.com/status/user_timeline/SaswatRoutroy.json?count=10", true);
$decode = json_decode($json, true);
echo "<pre>";
$count = count($decode); //counting the number of status
for($i=0;$i<$count;$i++)
{
echo $decode[$i]."<br>";
}
echo "</pre>";
?>
it throws me the error
A PHP Error was encountered
Severity: Warning
Message: file_get_contents(http://twitter.com/status/user_timeline/SaswatRoutroy.json?count=10) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found
Filename: views/recipy_detail.php
Line Number: 116
can anybody solve this for me
It looks to me like that URL is throwing a 404, and file_get_contents is accurately throwing an error.
Could you try replacing the URL with one that returns a successful JSON request.
You can see response to in your browser to URL http://twitter.com/status/user_timeline/SaswatRoutroy.json?count=10
{"errors":[{"message":"Sorry, that page does not exist","code":34}]}
User with username SaswatRoutroy is suspended now.
Twitter API was changed. You can get new documentation by URL