PHP mail() force single recipient - php

What is the best way to force mail() to send only to first recipient, even if user provides multiple recipients in $email... I need to filter user input somehow...?
$email = '1#mail.com, 2#mail.com, 3#mail.com...';
mail( $email, $subject, $body, $extra ) //send to: 1#mail.com

You may write:
$emails = explode(',',$email);
Now $emails[0] is the first email you can use in the mail() function.

You could explode the string by comma and only throw the first element of the resulting array in mail().
$email = '1#mail.com, 2#mail.com, 3#mail.com...';
$recips = explode(",", $email);
if(filter_var(trim($recips[0]), FILTER_VALIDATE_EMAIL) !== false) {
mail(trim($recips[0]), $subject, $body, $extra ) //send to: 1#mail.com
} else {
die("no valid email");
}

Imagine the user does not separate the adresses by using a comma. then this will not work and just trim()ing the adress will also not prevent you from giving multiple emails to mail().
You will somehow also need to check the adress to prevent syntax errors, f.e. using filter_var():
$emails = explode(',', $email);
$email = filter_var(trim($emails[0]), FILTER_VALIDATE_EMAIL);
if ($email === false) {
exit();
}
some more sophisticated checking can also be done using regular expressions:
$regex = "/^[a-zA-Z\d][\w\.-]*[a-zA-Z\d]#[a-zA-Z\d][\w\.-]*\.[a-zA-Z]{2,}$/i";
$emailString = '1#mail.com, 2#mail.com, 3#mail.com...';
$emailArray = explode(',', $emailString);
$isValdid = preg_match($regex, $emails[0]);
if ($isValid === 0) { // 1 for match, 0 for mismatch, false for error
echo "please supply a valid adress.";
}

Related

php mail not sending "invalid email address"

im getting the "invalid email address"
all is hardcoded for testing, what is missing? thanks!
<html>
<head><title>PHP Mail Sender</title></head>
<body>
<?php
/* All form fields are automatically passed to the PHP script through the array $HTTP_POST_VARS. */
$email = $HTTP_POST_VARS['example#example.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];
/* PHP form validation: the script checks that the Email field contains a valid email address and the Subject field isn't empty. preg_match performs a regular expression match. It's a very powerful PHP function to validate form fields and other strings - see PHP manual for details. */
if (!preg_match("/\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)) {
echo "<h4>Invalid email address</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ($subject == "") {
echo "<h4>No subject</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
}
/* Sends the mail and outputs the "Thank you" string if the mail is successfully sent, or the error string otherwise. */
elseif (mail($email,$subject,$message)) {
echo "<h4>Thank you for sending email</h4>";
} else {
echo "<h4>Can't send email to $email</h4>";
}
?>
</body>
</html>
Change
$email = $HTTP_POST_VARS['jaaanman2324#gmail.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];
to
$email ='jaaanman2324#gmail.com';
$subject ='subjectaaa';
$message = 'messageeeee';
I think you want it to be hardcoded like this:
$email = 'jaaanman2324#gmail.com';
Otherwise you are trying to get the value out of HTTP_POST_VARS with the key of jaaanman2324#gmail.com
First, don't use $HTTP_POST_VARS, it's $_POST now.
Second, by writing $HTTP_POST_VARS['jaaanman2324#gmail.com'] you're looking for table element with juanman234#gmail.com key.
That's not what you wanted to do.
If you want to hardcode it, write
$email = 'jaaanman2324#gmail.com';`
if not, write
$email = $_POST['email'];
to get email field from form.

Form not sending, function eregi() is deprecated [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I convert ereg expressions to preg in PHP?
Escape string to use in mail()
I am trying send my form, but I get this error...
Deprecated: Function eregi() is deprecated
I tried replacing it with preg_match(), but no luck. Here is my code:
$all_valid = $name_valid = $email_valid = $comments_valid = true;
if (isset($_POST['submit'])) {
if ($_POST['name'] == '') {
$all_valid = $name_valid = false;
}
if ($_POST['comments'] == '') {
$all_valid = $comments_valid = false;
}
if (!$validator->check_email_address($_POST['email'])) {
$all_valid = $email_valid = false;
}
if ($all_valid) {
// #### NO PROBLEMS FOUND - PROCESS THE FORM DATA HERE
$mail_to = 'cat30#hotmail.com'; // recipient address
$subject = "Email from website"; // email message subject line
$name = mysql_real_escape_string(trim($_POST['name'])); // sanitize the name
if (eregi("\r",$name) || eregi("\n",$name)){ // avoid email header injection
die();
}
$mail_from = mysql_real_escape_string(trim($_POST['email'])); // sanitize their email address
if (eregi("\r",$mail_from) || eregi("\n",$mail_from)){ // avoid email header injection
die();
}
$comments = htmlspecialchars(trim($_POST['comments'])); // convert HTML characters into entities
$headers = 'From: '. $mail_from. "\r\n";
mail($mail_to, $subject, $comments, $headers);
$response = '<h2>Thanks for contacting us, will get back to you soon</h2>';
}
}
It returns a slightly different value than eregi but if I'm reading your code correctly you should be able to use the strpos() function to determine if a substring exists in a string. Eregi ignores case so you might have to combine this with a strtolower($string) call too.
Something like this:
if (strpos("\r",strtolower($name)) || strpos("\n",strtolower($name)))

Issue filtering words in contact form PHP based

I having a issue filtering bad words inside a contact form message.
It strips all the message except the first letter of the word.
Any help?
below is just getting the info
<?php
$error = '';
if(!empty($_POST['username'])) $username = $_POST['username'];
if(!empty($_POST['email'])) $email = $_POST['email'];
if(!empty($_POST['subject'])) $subject = check($_POST['subject']);
if(!empty($_POST['message'])) $msg = filter($_POST['message']);
this is the function I am trying to use to strip the bad words and replace them
$bad_words = array(
'word1' => 'gosh',
'word2' => 'darn',);
function filter($matches) {
global $bad_words;
$replace = $bad_words[$matches[0]];
return !empty($replace) ? $replace : $matches[0];
}
checks the drop down options and doesn't allow certain subjects to be emailed.
function check($str){
global $error;
if ($str == 'Mean Spirited Comment'){
$error = 'You sent a Mean-Spirited Comment';
} else if ($str =='Political Comment'){
$error = 'You sent a Political Comment';
}
return $str;
}
places the info and sends
$to = 'email#email.com';
if (!empty($subject) && !empty($msg) && !empty($email) && !empty($username)){
if ($error == ''){
mail($to, $subject, $msg, 'From:' . $email);
} else {
print $error;
}
}
?>
You could use str_replace since it can take array.
For instance:
$message = "Hello there my good friends! I am very happy to see you all today even though I feel like crap.";
$badWords = array("Crap", "Damnit", "Frack");
echo str_replace($badWords, "*", $message);
Results would be: Hello there my good friends! I am very happy to see you all today even though I feel like *.
Why re-invent new methods when PHP already offers plenty of useful ones? This should be enough to remove "bad words" from messages being sent.

sending email with php

I got the following code and before sending i check the fields are populated or not...when sending the email i get the message 'We have received your email .' but i cannot see the email in my inbox, tried it with two different emails but same results... cannot figure out why can you help me please. here is the code:
if($badinput == NULL){ ?>
<h2>We have received your email .</h2>
</div>
<?php
require_once("libs/inc.email_form.php");
$email_fields = array(
"Name" => $_POST['name'],
"E-Mail Address" => $_POST['email'],
"Telephone Number" => $_POST['telephone'],
"Callback" => $_POST['callback'],
"Enquiry" => $_POST['enquiry']
);
contact_form( "myemail#yahoo.co.uk", $_POST['email'], " Enquiry", "test", $email_fields);
}
else
{
echo $badinput . "</div>";
}
?>
here is the function in libs/inc.email_form.php:
function contact_form($to, $from, $subject, $message, $fields){
if(!$to || !$from || !$subject || !$message || !$fields){
print form function is missing a variable";
return false;
}
$msg_body = $message."\n\nSubmitted ".date("l, F j, Y, g:i a")." [EST]\n\nSUBMISSION DETAILS:\n";
// clean up all the variables
foreach($fields as $k => $v){
$msg_body .= "\n".$k.": ".clean_var($v);
}
// add additional info
$referer = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : "could not determine" ;
$user_agent = (isset($_SERVER['HTTP_USER_AGENT'])) ? $_SERVER['HTTP_USER_AGENT'] : "could not determine" ;
$msg_body .= "\n\nAdditional Info:\nIP = ".$_SERVER['REMOTE_ADDR']."Browser Info: ".$user_agent."Referral: ".$referer." \r";
// send it
$emailer = new emailer;
if(is_array($to)){
foreach($to as $t){
$emailer->send_email($from, $subject, $msg_body, $to);
}
}else{
$emailer->send_email($from, $subject, $msg_body, $to);
}
return true;
}
I see no reason for using a class if it's just probably still using the standard PHP mail() function.
Please try using this code to test if mail actually get sent:
if (mail('you#domain.ext', 'subject', 'test email'))
echo 'Mail was sent';
else
echo 'Mail could not be sent';
Also please check the Spam folder as many emails send through PHP mail() get flagged as spam due to incorrect or incomplete headers or because of abuse and bad IP reputation (especially if you're using shared hosting).
It doesn't seem that your actually checking the return value from the $emailer class, so the function telling you your email is sent really is just a false positive.
I would change:
$emailer->send_email($from, $subject, $msg_body, $to);
to:
$result = $emailer->send_email($from, $subject, $msg_body, $to);
print_r($result);
and check what the $emailer class is returning. more then likely it's going to be a "0" for failed or "1" for success.
Is that a 100% accurate representation of your script?
There appears to be a major syntax error, which if it somehow doesn't error out on you, will at least totally change the script's functionality.
if(!$to || !$from || !$subject || !$message || !$fields){
print form function is missing a variable";
Surely, it should be:
if(!$to || !$from || !$subject || !$message || !$fields){
print "form function is missing a variable";

PHPList fails for email addresses with leading, trailing, or multiple adjacent dots

PHPList (version 2.10.17) fails to send messages to addresses that match one of the following formats:
my..Name#domain.com
myName.#domain.com
.myName#domain.com
the error message is Could not instantiate mail function.
The code in question is:
function MailSend($header, $body) {
$to = "";
for($i = 0; $i < count($this->to); $i++)
{
if($i != 0) { $to .= ", "; }
$to .= $this->to[$i][0];
}
if ($this->Sender != "" && (bool) ini_get("safe_mode") === FALSE)
{
$old_from = ini_get("sendmail_from");
ini_set("sendmail_from", $this->Sender);
$params = sprintf("-oi -f %s", $this->Sender);
$rt = #mail($to, $this->EncodeHeader($this->Subject), $body,
$header, $params);
}
else
$rt = #mail($to, $this->EncodeHeader($this->Subject), $body, $header);
if (isset($old_from))
ini_set("sendmail_from", $old_from);
if(!$rt)
{
$this->SetError($this->Lang("instantiate"));
return false;
}
return true;
}
The chosen code path is:
else
$rt = #mail($to, $this->EncodeHeader($this->Subject), $body, $header);
I could not reproduce this error on my own webserver where I set up PHPList for testing purposes.
Unfortunately the only system that is showing this behaviour is the production system. To add to that, I don't have access to any logfiles on that system - so I don't really know what is wrong.
My best guess is, that some sort of "string escape" on $to is needed to make this work, but I am somewhat reluctant to tamper with a production system (other than inserting some logging output).
Does anyone know a workaround for this sort of problem?
This is not an error, it is expected behavior. The local-part of an email address (the part before the #) may contain ., provided it is not the first nor the last character, and provided also that it does not appear two or more times consecutively. This means all three examples are invalid email addresses.
Read more about valid email addresses.

Categories