sending email with php - 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";

Related

php integrated function form mail validation doesnt work FILTER_VALIDATE_EMAIL

I have the following script that checks emails and do something with them if they are correct formatted.. I am using FILTER_VALIDATE_EMAIL for this
Here is the code:
if(!empty($_POST['maillist'])){
$_POST['maillist'] = 'mariatettamanti#gmail.com,
H0889#sofiaertel.com,sdfd#sfs.com,';
$mails = explode(',',$_POST['maillist']);
foreach($mails as $mail){
if(!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
echo $emailErr = $mail." - Invalid email format<br />";
}else{
echo 'do job with this mail';
}
}
}
As you can see mails are formatted as mails but the function prints only first mail as correct and the rest as wrong.. Why is that? What am I missing? Thanks
Problem is with last comma in your email address. It create and empty value at the end . To avoid this you use isset()
if (!empty($_POST['maillist'])) {
$_POST['maillist'] = 'H0889#sofisadatel.com,info#daddsadyomiaasdmi.com,info#hotsdaelmidasami.com,';
$mails = explode(',', $_POST['maillist']);
foreach ($mails as $mail) {
if (isset($mail) && $mail != "") {// check for empty email
if(!filter_var(trim($mail), FILTER_VALIDATE_EMAIL)) {
echo $emailErr = $mail . " - Invalid email format<br />";
} else {
echo 'do job with this mail';
}
}
}
}

Mail sent but attachment not received in wp_mail()

I am new in wordpress. I am trying to send a mail with an attachment. But every time the mail is being sent but the attachment is not. I searched almost all the post related to this topic here but all the solutions failed for me. I checked the path a lot of times and found that it is correct from 'uploads' folder. Please help me. This is my code,
<?php
if(isset($_POST['email'])){
$to = $_POST['email'];
$pdf = $_POST['pdf'];
$subject = "Presidency Alumni Annual Report";
$message = "Please download the attachment.";
$headers = 'From: Presidency Alumni Association Calcutta <noreply#presidencyalumni.com>' . "\n";
if($pdf == 'a'){
$attachments = array(WP_CONTENT_DIR . 'uploads/2015/01/Coffee-Mug-Banner.jpg');
}
else if($pdf == 'b'){
$attachments = array(WP_CONTENT_DIR . 'uploads/2014/08/Alumni-Autumn-Annual-2014.pdf');
}
else{
$attachments = array(WP_CONTENT_DIR . 'uploads/2014/08/Autumn-Annual-2012.pdf');
}
wp_mail($to, $subject, $message, $headers, $attachments);
print '<script type="text/javascript">';
print 'alert("Your Mail has been sent successfully")';
print '</script>';
}
?>
The most probable reason this to happen is if the condition if($pdf == 'a') {...} else if ($pdf == 'b') {...}) is not true. Check to see if this variable pdf is set properly in your post HTML form.
Also make sure that the constant WP_CONTENT_DIR contains something, i.e. is not empty string, because otherwise your path to the attachments will be invalid, i.e. it is better to access your uploads directory like this:
<?php $upload_dir = wp_upload_dir(); ?>
The $upload_dir now contains something like the following (if successful):
Array (
[path] => C:\path\to\wordpress\wp-content\uploads\2010\05
[url] => http://example.com/wp-content/uploads/2010/05
[subdir] => /2010/05
[basedir] => C:\path\to\wordpress\wp-content\uploads
[baseurl] => http://example.com/wp-content/uploads
[error] =>
)
Then, modify your code:
$attachments = array($upload_dir['url'] . '/2014/08/Autumn-Annual-2012.pdf');
See the documentation.

PHP mail() force single recipient

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.";
}

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.

PHPMailer Form Help

Is there any better way to stop spam coming through on my phpmailer script?
Also how would I go about adding formatting to this so its more readable when it gets sent through to email e.g. break lines
I hope my php syntax is correct - as i do not understand PHP.
<?php
# bool has_injection (String $var, [String $var, ...])
function has_injection () {
$values = func_get_args();
for ($i=0, $count=func_num_args(); $i<$count; $i++) {
if ( stristr($values[$i], "%0A") || stristr($values[$i], "%0D") || stristr($values[$i], "\\r") || stristr($values[$i], "\\n")
|| stristr($values[$i], "Bcc") || stristr($values[$i], "Content-Type") ) {
return true;
}
}
return false;
}
$error = '';
if (isset($_POST) && count($_POST)>0) {
# The form has been submitted
$course_title = $_POST['course_title'];
$course_date = $_POST['course_date'];
$course_code = $_POST['course_code'];
$course_fee = $_POST['course_fee'];
$break .= "\n";
$qual_subject_level = $_POST['qual_subject_level'];
$break .= "\n";
$email = $_POST['email'];
if ($name && $email && $subject) {
if (has_injection($name, $email, $subject)) {
# You've got another spammer at work here
$error = 'No spamming';
exit(0);
}
else {
# It's safe to send the message
mail('my#gmail.com',
$subject,
$course_title,
$course_code,
$course_fee,
$break,
$qual_subject_level,
$break,
$subject,
"From: $name <$email>");
}
}
else {
$error = 'Please fill in all the forms';
}
}
?>
One i use is have a text area and use your .css file to display:none it most bots dont read the css and thus think that the text box is shown and if it has content in it it's a bot if it does not then send your email.
E.G CSS
.antiBot{display:none};
HTML
<input type="text" class="antiBot" name="antibot" value="" />
PHP
<?php
if($_REQUEST['antibot'] == ""){
// send your email
}else{
// bot using your system
}
?>
How ever change the name or bot will get be able to notice its a trap and will get around it with little work insted of having to parse the CSS file for your site
So in your case just rap the if above around your code as for formatting of an email if its plain text use dubble quotes and \n (newline) but it wont work in single quotes.

Categories