PHP 7.0 STRPOS not functioning as expected - php

So, I was trying to use strpos to test if a string existed in a variable, but in all my attempts to make the if statement work, it was not succeeding, so I went about outputting the string and trying to find the point where strpos detected it, but it was not though it was clearly there! In this case I am searching an SMTP error output for the Gmail SMTP error code.I know how to fix the error, but I want my system to be able to parse smtp errors and report them to my users...
PHP Code:
$Request = RequestPasswordReset($_POST["email"]);
echo $Request;
echo "<br>Position of Error Code: " . strpos($Request, "gsmtp SMTP code: 550");
die();
if($Request === "SUCCESS") {
DisplayError("Password Reset Successful", "We have sent a email that contains a link to reset your password.", "/account/resetpassword.php");
} else if($Request === "USER_NOT_FOUND") {
DisplayError("Password Reset Request Failed", "The specified email is not tied to any accounts in our system.", "/account/resetpassword.php");
} else if(strpos($Request, "gsmtp SMTP code: 550") !== false) {
DisplayError("Password Reset Request Failed", "The mail was blocked by our relay due to IPs being not whitelisted.", "/account/resetpassword.php");
} else {
DisplayError("Password Reset Request Failed", "The request failed for an unknown reason.", "/account/resetpassword.php");
}
Text Output:
It does actually repeat itself, I echoed out the $Request twice and it did the following twice exactly
The following From address failed: XXXXXXX : MAIL FROM command failed,Invalid credentials for relay [XXXXXXX]. The IP address you've registered in your G Suite SMTP Relay service doesn't match domain of the account this email is being sent from. If you are trying to relay mail from a domain that isn't registered under your G Suite account or has empty envelope-from, you must configure your mail server either to use SMTP AUTH to identify the sending domain or to present one of your domain names in the HELO or EHLO command. For more information, please visit https://support.google.com/a/answer/6140680#invalidcred r126sm1314271qke.4 - gsmtp ,550,5.7.1SMTP server error: MAIL FROM command failed Detail: Invalid credentials for relay [XXXXXXX]. The IP address you've registered in your G Suite SMTP Relay service doesn't match domain of the account this email is being sent from. If you are trying to relay mail from a domain that isn't registered under your G Suite account or has empty envelope-from, you must configure your mail server either to use SMTP AUTH to identify the sending domain or to present one of your domain names in the HELO or EHLO command. For more information, please visit https://support.google.com/a/answer/6140680#invalidcred r126sm1314271qke.4 - gsmtp SMTP code: 550 Additional SMTP info: 5.7.1Position of Error Code:
(EDIT) Reset Password Request Function:
function RequestPasswordReset($Email) {
// Try to Get User
$User = GetUser_Email($Email);
// Does user exist?
if($User === "NOT_FOUND") {
return "USER_NOT_FOUND";
}
// Generate Link To Send with Email
$Link = GeneratePasswordResetLink();
$SendEmail = SendPasswordReset($User["Email"], $User["FirstName"] . $User["LastName"], $Link);
if($SendEmail !== "SUCCESS") {
return $SendEmail;
} else {
// WHAT IF MYSQL FAILS????? ~~~~~~~~~~~~~~~ NEED SOLOUTION
$PDO_Connection = CreateMySQLConnection();
$PDO_CMD = $PDO_Connection -> prepare("UPDATE accounts SET ResetPassword=? WHERE Email=?");
$PDO_CMD -> execute(array($Link, $User["Email"]));
return "SUCCESS";
}
}
(EDIT) Send Password Reset Function:
$User = GetUser_ResetID($resetID);
$mail = CreateSMTPConnection();
$mail->AddAddress($targetAddress, $targetName); // Add a recipient
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = 'LitenUp Password Reset';
$mail->Body = str_replace("https://mylitenup.net/account/resetpassword.php?ID=", ("https://mylitenup.net/account/resetpassword.php?ID=" . $resetID), file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/php/mailer/documents/resetpassword.html"));
$mail->AltBody = 'Reset Your Password: https://mylitenup.net/account/resetpassword.php?ID=' . $resetID;
$mail->XMailer = 'LitenUp Mailer';
$mail->XPriority = '1';
try{
$mail->send();
return "SUCCESS";
} catch (phpmailerException $e) {
return $e->errorMessage();
} catch (\Exception $e) {
return $e->getMessage();
}
(EDIT): I tried mb_strpos, but it is not working, so if that is what will work, why is it not working for me? I did mb_strpos($Request, "gsmtp SMTP code: 550");, but after execution it echos the request, but the Position of Error Code: line does not get echoed.
(Update 1): I really apologize for the delay, in a worst case I will extend this again with a bounty. However, you guys were right! When I first had the error, I outputted it and just copied the line "gsmtp SMTP code: 550", but after doing the tag there appears to be a new line of some sort. You can see in the that the line should be something more like "gsmtp" + + " SMTP code: 550", but I am not sure what the line break should be. I tried and \n.

The best solution would be to take the time to isolate exactly what character(s) is in that white-space.
Until you do that, you can just use regex to gloss over whatever is in there.
Change:
} else if(strpos($Request, "gsmtp SMTP code: 550") !== false) {
to:
} elseif(preg_match("/gsmtp\s+SMTP\s+code:\s+550/",$Request)) {

My best guess:
You're outputting to HTML, so it's possible that your CRLFs/LFs are rendering as spaces. I'd enclose your echo statements with <pre>...</pre> tags to see if it's the case. strpos would fail because you're searching for a space character where it's actually a CRLF/LF.

Related

Form to Email PHP Validation fallback using PHPMailer

i have a basic contact form on a website. i need to send the form results to 2 email addresses... 1) me, & 2) a confirmation to the person who submitted the form. the form results sent to the submitter has a different message in it.
i plan to add jQuery validation & Ajax but first i want to get the PHP to work. so i don't think i need a lot of PHP validation, just a basic - if critical fields are empty, then error message, as a fallback.
i'm using PHPMailer but unfortunately their documentation is sorely lacking for someone of my lack-of-php skills. but after much google'ing, i've been able to piece together something that mostly works. here is my code utilizing a small form (more fields to come later).
this DOES send the form to both email addresses - great!
the part i'm having trouble with is the validation & error/success messages.
if i just use the return $mail->send(); at the end of the function sendemail section, it sends fine. but if i try to submit the form without anything in the fields, nothing happens. so i tried adding this if(!$mail->send()) {...else...} piece i found somewhere, and it also works with valid form info, but not if empty.
so, what should i use instead of this? or would it be something different to the end if/else part?
<?php
if (isset($_POST['submit'])) {
date_default_timezone_set('US/Central');
require 'PHPMailer-5.2.26/PHPMailerAutoload.php';
function sendemail(
$SK_emailTo,
$SK_emailSubject,
$SK_emailBody
) {
$mail = new PHPMailer;
$mail->setFrom('myEmail#gmail.com', 'My Name');
$mail->addReplyTo($_POST['email'], $_POST['name']);
$mail->addAddress($SK_emailTo);
$mail->Subject = $SK_emailSubject;
$mail->Body = $SK_emailBody;
$mail->isHTML(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Username = 'myEmail#gmail.com';
$mail->Password = 'myPwd';
//return $mail->send(); //this works by itself, without IF/ELSE, but doesn't return error if empty form fields
if(!$mail->send()) {
return 'There is a problem' . $mail->ErrorInfo;
}else{
return 'ok'; // this works but i don't know why
}
} //end function sendemail
// form fields to variables
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// from function sendmail to ASSIGN VALUES to...
/* $SK_emailTo,
SK_emailSubject,
$SK_emailBody */
if (sendemail(
'myEmail#address.com',
'First email subject',
'Form results to me...
<br><br>'.$message
)) {
sendemail(
$email,
'Second email subject',
'Confirmation email to person who submitted the form...
<br><br>'.$message
);
$msg = 'Email sent!';
} else {
$msg = 'Email failed!' . $mail->ErrorInfo;
}
} //end if submit
?>
as a sidenote, why does the return 'ok'; work? what does the 'ok' part attach to?
thanks!
//////////////////////// EDIT: NEW INFO BUT STILL NOT SOLVED ////////////////////////
based on the suggestions & edits by Mauro below (and in that posts comments), here is where i'm at now...
<?php
if (isset($_POST['submit'])) {
date_default_timezone_set('US/Central');
require 'PHPMailer-5.2.26/PHPMailerAutoload.php';
function sendemail(
$SK_emailTo,
$SK_emailSubject,
$SK_emailBody
) {
$mail = new PHPMailer(true);
$mail->setFrom('myEmail#gmail.com', 'My Name');
$mail->addReplyTo($_POST['email'], $_POST['name']);
$mail->addAddress($SK_emailTo);
$mail->Subject = $SK_emailSubject;
$mail->Body = $SK_emailBody;
$mail->isHTML(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->Username = 'myEmail#gmail.com';
$mail->Password = 'myPwd';
return $mail->send();
} //end function sendemail
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
try {
sendemail(
'myEmail#address.com',
'First email subject',
'Form results to me...
<br><br>'.$message
);
sendemail(
$email,
'Second email subject',
'Confirmation email to person who submitted the form...
<br><br>'.$message
);
echo 'Email sent!';
} //end try
catch (phpmailerException $e) { //catches PHPMailer errors
echo 'There is a problem; the message did NOT send. Please go back and check that you have filled in all the required fields and there are no typos in your email address.';
echo $e->errorMessage();
}
catch (Exception $e) { //catches validation errors
echo 'There is a problem; the message did NOT send. Please either go back and try again or contact us at email#address.com';
echo $e->getMessage();
}
function validateEmpty($string, $name = 'name') {
$string = trim($string);
if ($string == '') {
throw new Exception(sprintf('%s is empty.', $name));
}
}
} //end if submit
?>
STILL...
1) Mauro suggested i log the error message using use error_log(). how do i do that? is that what produces the text file of error messages in the ftp directory?
2) Mauro also suggested using an $error & $success flag. what is that & how do i do it?
3) i want to have the custom error message in the above catch if the "name" &/or "email" fields (& possibly others) are simply empty. Mauro wrote the function validateEmpty code above, but i can't get it to work. do i have it in the wrong placement within the script or doing something else wrong with it?
3b) it looks to me like this function is just for the "name" field, do i have to duplicate it for the "email" field?
PLEASE REMEMBER...
i want to be able to have a SIMPLE validation here as a fallback in case Javascript/Jquery isn't working for some reason.
also note that the above DOES "send" the email correctly; so am now just trying to get the validation & error message to work right.
thank you for your time & expertise!
tl;dr: both statements evaluate to true. It's better to return true or false instead of strings and handle the message later.
First I'll take care of your question, then I'll make some suggestions on good practices.
When you use return x; in PHP and most languages, you're "sending" x back to where you called the function. So, when your code is executed it will be read as:
if('ok')
or
if ('Error info...')
PHP evaluates the condition on an if statement (this is the part between parenthesis) as true or false by converting it to the boolean type. The string to boolean conversion in PHP is basically as follows: any non-empty string evaluates as TRUE (follow the link, check first table, last column).
So, your function is returning 'ok' if it succeeds, 'Error info...' if it fails, these are both non-empty strings and thereof evaluated as true, so no matter if the first email sending attempt went well, your script will try to send the second one, and will always set $msg to 'Email sent!'.
Here's some advice on how to fix your script so it works (and looks) better:
As #Matt suggested it's always best to validate the data by yourself instead of relying on PHPMailer to do so. Despite PHPMailer will return an error if the destination address is invalid, it's a good practice not to even call the library if the email is not valid. So:
First, validate the data using javascript, so your user get's instant feedback.
Then, validate it using PHP (maybe create a new validate() function that may use filter_var() to validate emails.
Last, send the email only if the previous two were successful.
To follow your chain of thought, you should be evaluating if the string returned by sendemail() equals to 'ok' or not:
if (sendemail(...) == 'ok')
But, instead of evaluating two different strings ('ok' or 'Error info...') it's better if the function returned boolean values instead, and since PHPMailer's send() already does, just keep it as you have it commented:
return $mail->send()
Your last line is using $mail, a variable that you declared inside a function and you never made global, so it won't be available at that point and since you're trying to get a property (ErrorInfo) you'll be firing two PHP notices: Undefined variable and Trying to get a property from a non-object. You COULD just add global $mail at the top of the function and that will make it globally available (outside your function's scope) but this is considered a bad practice since in large pieces of code you might get confused.
Instead, a neater way of firing the error would be to throw/catch an exception:
function sendemail(...) {
// ... PHPMailer config ...
if ($mail->send()) {
return true;
} else {
throw Exception('Error: ' + $mail->ErrorInfo);
}
}
// later...
try {
sendemail()
$msg = 'Email sent!';
} catch (Exception $e) {
$msg = 'Email failed!' . $e->getMessage();
}
Here, if there's a problem with the emails sending, your function will throw a generic exception and the catch part will be executed.
EVEN BETTER
If you initialize PHPMailer like this:
$mail = new PHPMailer(true); // note the parameter set to true.
It will throw an exception by itself if it fails to send the email and you'll be able to catch the exception:
function sendemail(...) {
$mail = PHPMailer(true); // this line
// ... PHPMailer config ...
return $mail->send(); // just to return something, we aren't really using this value anymore.
}
// later...
try {
sendemail(...)
$msg = 'Email sent!';
} catch (phpmailerException $e) {
echo $e->errorMessage(); // Catch PHPMailer exceptions (email sending failure)
} catch (Exception $e) {
echo $e->getMessage(); // Boring error messages from anything else!
}
Never forget to read the docs!

PHP - Verifying emails existance [duplicate]

I have a question, i have a php script to check if the email address exist.
But appear that yahoo, hotmail, aol and others providers are accepting any emails and not rejecting the invalid emails.
Only Gmail, and many domains like stackoverflow.com are rejecting the no vaild emails.
Check my script and let me know if i can do some to check the yahoo and others.
html post form
<html>
<body>
<form action="checkemail.php" method="POST">
<b>E-mail</b> <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
php
<?php
/* Validate an email address. */
function jValidateEmailUsingSMTP($sToEmail, $sFromDomain = "gmail.com", $sFromEmail = "email#gmail.com", $bIsDebug = false) {
$bIsValid = true; // assume the address is valid by default..
$aEmailParts = explode("#", $sToEmail); // extract the user/domain..
getmxrr($aEmailParts[1], $aMatches); // get the mx records..
if (sizeof($aMatches) == 0) {
return false; // no mx records..
}
foreach ($aMatches as $oValue) {
if ($bIsValid && !isset($sResponseCode)) {
// open the connection..
$oConnection = #fsockopen($oValue, 25, $errno, $errstr, 30);
$oResponse = #fgets($oConnection);
if (!$oConnection) {
$aConnectionLog['Connection'] = "ERROR";
$aConnectionLog['ConnectionResponse'] = $errstr;
$bIsValid = false; // unable to connect..
} else {
$aConnectionLog['Connection'] = "SUCCESS";
$aConnectionLog['ConnectionResponse'] = $errstr;
$bIsValid = true; // so far so good..
}
if (!$bIsValid) {
if ($bIsDebug) print_r($aConnectionLog);
return false;
}
// say hello to the server..
fputs($oConnection, "HELO $sFromDomain\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['HELO'] = $oResponse;
// send the email from..
fputs($oConnection, "MAIL FROM: <$sFromEmail>\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['MailFromResponse'] = $oResponse;
// send the email to..
fputs($oConnection, "RCPT TO: <$sToEmail>\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['MailToResponse'] = $oResponse;
// get the response code..
$sResponseCode = substr($aConnectionLog['MailToResponse'], 0, 3);
$sBaseResponseCode = substr($sResponseCode, 0, 1);
// say goodbye..
fputs($oConnection,"QUIT\r\n");
$oResponse = fgets($oConnection);
// get the quit code and response..
$aConnectionLog['QuitResponse'] = $oResponse;
$aConnectionLog['QuitCode'] = substr($oResponse, 0, 3);
if ($sBaseResponseCode == "5") {
$bIsValid = false; // the address is not valid..
}
// close the connection..
#fclose($oConnection);
}
}
if ($bIsDebug) {
print_r($aConnectionLog); // output debug info..
}
return $bIsValid;
}
$email = $_POST['email'];
$bIsEmailValid = jValidateEmailUsingSMTP("$email", "gmail.com", "email#gmail.com");
echo $bIsEmailValid ? "<b>Valid!</b>" : "Invalid! :(";
?>
If you need to make super sure that an E-Mail address exists, send an E-Mail to it. It should contain a link with a random ID. Only when that link is clicked, and contains the correct random ID, the user's account is activated (or ad published, or order sent, or whatever it is that you are doing).
This is the only reliable way to verify the existence of an E-Mail address, and to make sure that the person filling in the form has access to it.
There is no 100% reliable way of checking the validity of an email address. There are a few things you can do to at least weed out obviously invalid addresses, though.
The problems that arise with email addresses is actually very similar to those of snail mail. All three points below can also be used for sending snail mail (just change the DNS record with a physical address).
1. Check that the address is formatted correctly
It is very difficult to check the format of email addresses, but PHP has a validation filter that attempts to do it. The filter does not handle "comments and folding whitespace", but I doubt anyone will notice.
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE) {
echo 'Valid email address formatting!';
}
2. Check that the DNS record exists for the domain name
If a DNS (Domain Name System) record exists then at least someone has set it up. It does not mean that there is an email server at the address, but if the address exists then it is more likely.
$domain = substr($email, strpos($email, '#') + 1);
if (checkdnsrr($domain) !== FALSE) {
echo 'Domain is valid!';
}
3. Send a verification email to the address
This is the most effective way of seeing if someone is at the other end of the email address. If a confirmation email is not responded to in an orderly fashion -- 3 hours for example -- then there is probably some problem with the address.
You can validate "used or real" emails with Telnet and MX records more info in here, for PHP exists a great library call php-smtp-email-validation that simplify the process.
You create a boolean function with the file example1.php and call it when you'll validate the email text. For Gmail, Hotmail, Outlook, live and MSM I don's have any problems but with Yahoo and Terra the library can't validate correctly emails
The problem is gmail uses port 25 for their smtp outgoing mails, the other providers use different ports for their connection. Your response seems okay for gmail.com.
When you connect to gmail smtp it gives you response 250 2.1.5 OK j5si2542844pbs.271 - gsmtp
But when you connect to any other smtp who does not use port 25 it gives you null response.

Can not send email threw SwiftMailer with Mandrill

Since today, many of my php applications can not send email using SwiftMailer and different Mandrill accounts.
I've got this code, and the send function in the last if stop the script..
// Instance message
$message = Swift_Message::newInstance();
$message->setSubject("subject")
->setFrom(array('noreply#email.test' => 'test'))
->setTo(array('a_valid_email' => 'name'))
->setBody("test", 'text/html')
->setPriority(2);
$smtp_host = 'smtp.mandrillapp.com';
$smtp_port = 587;
$smtp_username = 'valid_username';
$smtp_password = 'valid_password';
// SMTP
$smtp_param = Swift_SmtpTransport::newInstance($smtp_host , $smtp_port)
->setUsername($smtp_username)
->setPassword($smtp_password);
// Instance Swiftmailer
$instance_swiftmailer = Swift_Mailer::newInstance($smtp_param);
$type = $message->getHeaders()->get('Content-Type');
$type->setValue('text/html');
$type->setParameter('charset', 'iso-8859-1');
//Here the send function stop event and I did not go inside the if
if ($instance_swiftmailer->send($message, $fail)) {
echo 'OK ';
}else{
echo 'NOT OK : ';
print_r($fail);
}
Thank you in advance to help me to solve this problem..
If your code used to work, and now doesn't work, and you didn't change your code, then it's probably not a problem with your code. Check your Mandrill account validity - sometimes they suspend accounts for suspicious-appearing usage.

How to Validate email address exist or not in php? [duplicate]

I have a question, i have a php script to check if the email address exist.
But appear that yahoo, hotmail, aol and others providers are accepting any emails and not rejecting the invalid emails.
Only Gmail, and many domains like stackoverflow.com are rejecting the no vaild emails.
Check my script and let me know if i can do some to check the yahoo and others.
html post form
<html>
<body>
<form action="checkemail.php" method="POST">
<b>E-mail</b> <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
php
<?php
/* Validate an email address. */
function jValidateEmailUsingSMTP($sToEmail, $sFromDomain = "gmail.com", $sFromEmail = "email#gmail.com", $bIsDebug = false) {
$bIsValid = true; // assume the address is valid by default..
$aEmailParts = explode("#", $sToEmail); // extract the user/domain..
getmxrr($aEmailParts[1], $aMatches); // get the mx records..
if (sizeof($aMatches) == 0) {
return false; // no mx records..
}
foreach ($aMatches as $oValue) {
if ($bIsValid && !isset($sResponseCode)) {
// open the connection..
$oConnection = #fsockopen($oValue, 25, $errno, $errstr, 30);
$oResponse = #fgets($oConnection);
if (!$oConnection) {
$aConnectionLog['Connection'] = "ERROR";
$aConnectionLog['ConnectionResponse'] = $errstr;
$bIsValid = false; // unable to connect..
} else {
$aConnectionLog['Connection'] = "SUCCESS";
$aConnectionLog['ConnectionResponse'] = $errstr;
$bIsValid = true; // so far so good..
}
if (!$bIsValid) {
if ($bIsDebug) print_r($aConnectionLog);
return false;
}
// say hello to the server..
fputs($oConnection, "HELO $sFromDomain\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['HELO'] = $oResponse;
// send the email from..
fputs($oConnection, "MAIL FROM: <$sFromEmail>\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['MailFromResponse'] = $oResponse;
// send the email to..
fputs($oConnection, "RCPT TO: <$sToEmail>\r\n");
$oResponse = fgets($oConnection);
$aConnectionLog['MailToResponse'] = $oResponse;
// get the response code..
$sResponseCode = substr($aConnectionLog['MailToResponse'], 0, 3);
$sBaseResponseCode = substr($sResponseCode, 0, 1);
// say goodbye..
fputs($oConnection,"QUIT\r\n");
$oResponse = fgets($oConnection);
// get the quit code and response..
$aConnectionLog['QuitResponse'] = $oResponse;
$aConnectionLog['QuitCode'] = substr($oResponse, 0, 3);
if ($sBaseResponseCode == "5") {
$bIsValid = false; // the address is not valid..
}
// close the connection..
#fclose($oConnection);
}
}
if ($bIsDebug) {
print_r($aConnectionLog); // output debug info..
}
return $bIsValid;
}
$email = $_POST['email'];
$bIsEmailValid = jValidateEmailUsingSMTP("$email", "gmail.com", "email#gmail.com");
echo $bIsEmailValid ? "<b>Valid!</b>" : "Invalid! :(";
?>
If you need to make super sure that an E-Mail address exists, send an E-Mail to it. It should contain a link with a random ID. Only when that link is clicked, and contains the correct random ID, the user's account is activated (or ad published, or order sent, or whatever it is that you are doing).
This is the only reliable way to verify the existence of an E-Mail address, and to make sure that the person filling in the form has access to it.
There is no 100% reliable way of checking the validity of an email address. There are a few things you can do to at least weed out obviously invalid addresses, though.
The problems that arise with email addresses is actually very similar to those of snail mail. All three points below can also be used for sending snail mail (just change the DNS record with a physical address).
1. Check that the address is formatted correctly
It is very difficult to check the format of email addresses, but PHP has a validation filter that attempts to do it. The filter does not handle "comments and folding whitespace", but I doubt anyone will notice.
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE) {
echo 'Valid email address formatting!';
}
2. Check that the DNS record exists for the domain name
If a DNS (Domain Name System) record exists then at least someone has set it up. It does not mean that there is an email server at the address, but if the address exists then it is more likely.
$domain = substr($email, strpos($email, '#') + 1);
if (checkdnsrr($domain) !== FALSE) {
echo 'Domain is valid!';
}
3. Send a verification email to the address
This is the most effective way of seeing if someone is at the other end of the email address. If a confirmation email is not responded to in an orderly fashion -- 3 hours for example -- then there is probably some problem with the address.
You can validate "used or real" emails with Telnet and MX records more info in here, for PHP exists a great library call php-smtp-email-validation that simplify the process.
You create a boolean function with the file example1.php and call it when you'll validate the email text. For Gmail, Hotmail, Outlook, live and MSM I don's have any problems but with Yahoo and Terra the library can't validate correctly emails
The problem is gmail uses port 25 for their smtp outgoing mails, the other providers use different ports for their connection. Your response seems okay for gmail.com.
When you connect to gmail smtp it gives you response 250 2.1.5 OK j5si2542844pbs.271 - gsmtp
But when you connect to any other smtp who does not use port 25 it gives you null response.

CakePHP email not working properly - how to track the error

I using cakephp email component. In my live server $this->Email->send() return success. but mail is not receiving. what is the problem?? i need to find whats the error ?
My controller not have any model this may cause any problem for emails ?
$this->Email->from = 'Mysitename <no-reply#mysite.com';
$this->Email->to = 'sample#gmail.com';
$this->Email->subject = "This is test";
$this->Email->template = 'template_name';
$this->Email->sendAs = 'html';
ob_start();
if($this->Email->send())
{
$this->log(' Mail Success');
}
else
{
$this->log('Something broke in mail');
}
ob_end_clean();
You can set delivery to debug to see an output of your message to make sure it's fine:
$this->Email->delivery = 'smtp';
And you also need to setFlash('email') to see the output in your view:
echo $this->Session->flash('email');
As far as emailing from a live server goes - there's a very good chance the server or IP is blacklisted and you'll need to get it to pass various checks before your sent messages can be received:
http://www.digitalsanctuary.com/tech-blog/debian/setting-up-spf-senderid-domain-keys-and-dkim.html

Categories