PHP Foreach Loop mail() - php

My following script runs fine when a single email address is entered into the textarea, but once two are entered, no emails are sent. What am I doing wrong?
if($_POST['submit']=='Send Email') {
$email_addresses = explode(",\n", $_POST['email']);
foreach($email_addresses as $email_address){
$email_address = trim($email_address);
send_mail( 'noreply#noreply.com',
$email_address,
'Test Email',
"Hello This Email Is A Test");
}
}
var_dump($email_addresses) results in this
array(1) { [0]=> string(39) "email1#test.com email2#test.com" }

You're using the same variable name twice
foreach($email_addresses as $email_addresses)
so on the second loop, the source is overwritten
Edit:
please post the output of
var_dump($_POST['email']);
var_dump(explode(",\n", $_POST['email']));

It should be:
foreach($email_addresses as $email_address){
$email_address = trim($email_address);
send_mail( 'noreply#noreply.com',
$email_address,
'Test Email',
"Hello This Email Is A Test");
}
Also splitting using explode on ",\n" separator isn't a good idea (people can send ",\r\n" in some cases). Provide multiple fields or use preg_split().
If it doesn't work try var_dump($email_address); after the explode() function to get the information what exactly happens with the input (and so you can see that input is actually correct).
UPDATE: As you can clearly see there is no \n in $email_address. It depends on your HTML form.
For a quick fix just explode(', ', $email_addresses); Also - you missed , in your input, which you require to explode that string.

obviously a#b.com b#c.com is not a valid email, and my psychic powers tell me that this is not the correct way to do this. What if I enter something else than an email address? Try to sanitise the data you receive from user. You can not trust user input blindly.

foreach($email_addresses as $email_addresses){
Means that you are overwriting the source array ($email_addresses) with the first entry in the array, because they are the same variable name. Unfortunately, PHP throw an error on this, so you end up rewriting your array with the first email address, and then prematurely (to your needs) exiting the loop (though this is expected and logical behaviour).

Related

PHP change string parsed from email

Using a PHP script file to filter emails. Everything is working properly, but it seems that if I were to initiate a conversation between a cell phone (Verizon Wireless) and the SMTP server, Verizon changes the format of outgoing messages.
For example, I need to respond to an email using XXX#vtext.com but Verizon will respond with XXX#vzwpix.com which cannot be responded to. So I created the following code to try and remove and replace the #vzwpix.com but it still isn't sending the mail. I know the code is working however because if I change the $from in the mail function to XXX#vtext.com the code works and sends the message.
//Parse "from"
$from1 = explode ("\nFrom: ", $email);
$from2 = explode ("\n", $from1[1]);
if(strpos ($from2[0], '<') !== false)
{
$from3 = explode ('<', $from2[0]);
$from4 = explode ('>', $from3[1]);
$from = $from4[0];
}
else
{
$from = $from2[0];
}
if(strpos ($from[1], '#vzwpix.com') !== false) {
str_replace('#vzwpix.com', '#vtext.com', $from);
}
var_dump( mail( $from, "Hi", "What is the email:"));
I am using var_dump just for developmental purposes by the way.
I did some research and I think the best way to do this maybe is to explode the XXX#vzwpix.com at the # symbol, then run a str_replace('vzwpix.com','vtext.com', $from5); However, that didn't work and then I thought maybe implode it after running a str_replace?
If the bad domains are static, why don't you explode on 'vzwpix' and then implode on 'vtext'? This should replace each of the bad instances in you address string.
You forgot to get the result of your str_replace
$from_with_vtext=str_replace('#vzwpix.com', '#vtext.com', $from[1]);

Find first position where pattern matching failed.

i am trying to find the common errors users have while entering email ids. I can always validate EMAIL using PHP Email Filter
$email = "someone#exa mple.com";
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "E-mail is not valid";
}
else
{
echo "E-mail is valid";
}
or pattern matching
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
I agree that these are not full proof ways to validate emails. However they should capture 80% of cases.
What I want is - Which position email became invalid? if its a space, at what position user had entered space. or did it fail because of "." in the end?
Any pointers?
-Ajay
PS : I have seen other thread regarding email validations. I can add complexity and make it 100%. concern here is to capture the most common mistakes made by people when entering Email ID.
This is difficult because sometimes it's not always a single character that makes an email address invalid. The example you give could easily be solved by:
$position = strpos('someone#exa mple.com', ' ');
However, it seems you are not interested in an all encompassing solution but rather something that will catch the majority of character based errors. I would take the approach of using the regular expression but capture each section of the email address in a sub pattern for further validation. For example:
$matches = null;
$result = preg_match("/(([\w\-]+)\#([\w\-]+)\.([\w\-]+))/", $email, $matches);
var_dump($matches);
By capturing sections of the regex validation in sub patterns you could then dive further into each section and run similar or different tests to determine where the user went wrong. For example you could try and match up the TLD of the email address against a whitelist. Of course there are also much more robust email validators in frameworks like Zend or Symfony that will tell you more specifically WHY an email address is not valid, but in terms of knowing which specific character position is at fault (assuming it's a character that is at fault) I think a combination of tactics would work best.
There is no way I know of in Java to report back the point at which a regex failed. What you could do is start building a set of common errors (as described by Manu) that you can check for (this might or might not use regex expressions). Then categorize into these known errors and 'other', counting the frequency of each. When an 'other' error occurs, develop a regex that would catch it.
If you want some assistance with tracking down why the regex failed you could use a utility such as regexbuddy, shown in this answer.
Just implement some checks on your own:
Point at the end:
if(substr($email, -1) == '.')
echo "Please remove the point at the end of you email";
Spaces found:
$spacePos = strpos($email, ' ');
if(spacePos !== false)
echo "Please remove the space at pos: ".$spacePos;
And so on...
First of all, I would like to say that the reason your example fails is not the space. It is the lack of '.' in former part and lack of '#' in the latter part.
If you input
'someone#example.co m' or 's omeone#example.com', it will success.
So you may need 'begin with' and 'end with' pattern to check strictly.
There is no exist method to check where a regular expression match fails as I know since check only gives the matches, but if you really want to find it out , we can do something by 'break down' the regular expression.
Let's take a look at your example check.
preg_match ("/^[\w\-]+\#[\w\-]+\.[\w\-]+$/",'someone#example.com.');
If it fails, you can check where its 'sub expression' successes and find out where the problem is:
$email = "someone#example.com.";
if(!preg_match ("/^[\w\-]+\#[\w\-]+\.[\w\-]+$/",$email)){ // fails because the final '.'
if(preg_match("/^[\w\-]+\#[\w\-]+\./",$email,$matches)){ // successes
$un_match = "[\w\-]+"; // What is taken from the tail of the regular expression.
foreach ($matches as $match){
$email_tail = str_replace($match,'',$email); // The email without the matching part. in this case : 'com.'
if(preg_match('/^'.$un_match.'/',$email_tail,$match_tails)){ // Check and delete the part that tail match the sub expression. In this example, 'com' matches /[\w\-]+/ but '.' doesn't.
$result = str_replace($match_tails[0],'',$email_tail);
}else{
$result = $email_tail;
}
}
}
}
var_dump($result); // you will get the last '.'
IF you understand the upper example, then we can make our solution more common, for instance, something like below:
$email = 'som eone#example.com.';
$pattern_chips = array(
'/^[\w\-]+\#[\w\-]+\./' => '[\w\-]+',
'/^[\w\-]+\#[\w\-]+/' => '\.',
'/^[\w\-]+\#/' => '[\w\-]+',
'/^[\w\-]+/' => '\#',
);
if(!preg_match ("/^[\w\-]+\#[\w\-]+\.[\w\-]+$/",$email)){
$result = $email;
foreach ($pattern_chips as $pattern => $un_match){
if(preg_match($pattern,$email,$matches)){
$email_tail = str_replace($matches[0],'',$email);
if(preg_match('/^'.$un_match.'/',$email_tail,$match_tails)){
$result = str_replace($match_tails[0],'',$email_tail);
}else{
$result = $email_tail;
}
break;
}
}
if(empty($result)){
echo "There has to be something more follows {$email}";
}else{
var_dump($result);
}
}else{
echo "success";
}
and you will get output:
string ' eone#example.com.' (length=18)

PHP: Email Parsing - Multiple Recipients

I am piping email that get's sent to my server to a PHP script. The script parses the email so I can assign variables.
My problem is once in awhile somebody will include my email address to an email that's getting sent to multiple recipients and my script will only get the first one. I need it to find my email address then assign it to a variable.
Here is what the email array looks like: http://pastebin.com/0gdQsBYd
Using the example above I would need to get the 4th recipient: my_user_email#mydomain.com
Here is the code I am using to get the "To -> name" and "To -> address"
# Get the name and email of the recipient
$toName = $results['To'][0]['name'];
$toEmail = $results['To'][0]['address'];
I assume I need to do a foreach($results['To'] as $to) then a preg_match but I am not good with regular expressions to find the email I want.
Some help is appreciated. Thank you.
Instead of usin preg_match inside foreach loop you can use strstr like below
Supposing you are looking for my_user_email#mydomain.com use following code
foreach($results['To'] as $to)
{
// gets value occuring before the #, if you change the 3 rd parameter to false returns domain name
$user = strstr($to, '#', true) ;
if($user == 'my_user_email')
{
//your action code goes here
}
}
example:
<?php
$email = 'name#example.com';
$domain = strstr($email, '#');
echo $domain; // prints #example.com
$user = strstr($email, '#', true); // As of PHP 5.3.0
echo $user; // prints name
?>
Actually, you do not need to use a regexp at all. Instead you can use a PHP for statement that loops through your array of To addresses.
$count = count($root['To']);
for ($i=0; $i < $count; $i++) {
//Do something with your To array here using $root['To'][$i]['address']
}

Why does PHP filter_var say that this is a valid email address?

I use the filter_var PHP function to validate email address when a user signs up to my site.
I use this code from the post:
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
then later I do:
if(!$email) {
// return to the form
}
else {
// send registration info
}
now when I var_dump($email), I get the output:
string(23) "user."name"#example.com"
I would like to know why this does not return false. I think the double quotes are not acceptable, so why does PHP say it’s valid?
It is a valid email address :
A quoted string may exist as a dot separated entity within the
local-part or it may exist when the outermost quotes are the outermost
chars of the local-part (e.g. abc."defghi".xyz#example.com or
"abcdefghixyz"#example.com are allowed. abc"defghi"xyz#example.com is
not; neither is abc\"def\"ghi#example.com).
I had the same problem (see Dalmas on why it's valid) and here's how I fixed it:
filter_var($email, FILTER_SANITIZE_EMAIL);
eg:
$email = 'user."name"#example.com';
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
will output:
string(21) "user.name#example.com"
Then you can validate the email using your validation.
you can get more information on the php site

How to have a variable in a mail line

okay, here is the code
while (!feof($text)) {
$name = fgets($text);
$number = fgets($text);
$carrier = fgets($text);
$date = fgets($text);
$line = fgets($text);
$content = $_POST['message'];
$message .= $content;
$message .= "\n";
$number = $number;
mail("$number#vtext.com", "Event Alert", $message, "SGA");
Header("Location: mailconf.php");
}
I am trying to get a message sent to a phone, I have 'message' coming in from a text area, and then I assign it to "$content" then I put "$content" into "$message" and then as you can see, in my mail line, I want the address to be the variable "number"#vtext.com I have the while loop because there are many people in these files I wish to send a message to...
When I change the "$number#vtext.com" to my email address, it sends everything fine, I just cannot seem to get it to send to a phone number, please help!
thanks!
The problem is that fgets includes the newline character as part of the return. So you are effectively sending an email to:
1234567890
#vtext.com
Which of course is invalid. Change your line that reads $number = $number to:
$number = trim($number);
And the rest of your code should function as expected, with the email being received on your phone.
Part of my original answer
I would highly recommend using a (probably paid) service to send SMS messages to phones if you need anything remotely reliable. A quick search yielded a few results:
PHP/SMS Tutorial
A list of 5 ways to Text for free <-- This link is dated, but might still be helpful
You need to append the number variable and the "#vtext.com" literal string together:
mail($number . "#vtext.com", "Event Alert", $message, "SGA");

Categories