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.
Related
I have customize mailer function where except file attachment, rest of things are working well. To make it simplify, I have added only code related to attachment. As output, I can see file uploaded to server but it's going to attach in email. I am getting all details in email except file attachment. it's customize mailer class which I have created but not sure why attachment not sending to email.
Mailer.class.php
<?php
class Mailer
{
private $addAttachment = [];
public function addAttachment($addAttachment)
{
if (empty($addAttachment))
{
$this->setError('No Attachments','empty');
}else{
$this->addAttachment[] = $addAttachment;
echo $addAttachment;
}
return $this;
}
}
For Sending test.php
require_once 'Mailer.class.php';
$toemails = array("my_email_address#gmail.com");
$toemail = implode(',', $toemails);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$attachment = $_FILES["uploaded_file"]["tmp_name"];
$folder = '/uploads/';
$file_name1 = $_FILES["uploaded_file"]["name"];
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], "$folder".$_FILES["uploaded_file"]["name"]);
print_r($_FILES);
$mailer = new Mailer(true);
$mailer->setToEmail($toemail)
->setFromName(isset($_POST['fname'])?$_POST['fname']:'')
->setFromEmail(isset($_POST['email'])?$_POST['email']:'')
->setSubject('Application Regarding'.$_POST['Title'])
->addAttachment('/uploads/'.$_FILES["uploaded_file"]["name"])
->setBody($body)
->run();
exit();
if(!$mailer->sendMail()) {
echo "Something has gone wrong, please contact the site administrator or try again.";
}
else {
echo "Email Successfully Submitted";
}
print "</pre>";
}
?>
print_r($_FILES) gives me following Output for attachment:
Array
(
[uploaded_file] => Array
(
[name] => Image_Manager.pdf
[type] => application/pdf
[tmp_name] => /tmp/phplBV7gV
[error] => 0
[size] => 150300
)
)
Here is the issue. I am trying to troubleshoot an issue in my PHP script that prevents it from emailing the info, our client has inputted.
<?php
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$recaptcha=$_POST['g-recaptcha-response'];
if(!empty($recaptcha))
{
include("getCurlData.php");
$google_url="https://www.google.com/recaptcha/api/siteverify";
$secret='6LegpgYTAAAAABK9Nd45_DfAPu7_gwHro9pj902B';
$ip=$_SERVER['REMOTE_ADDR'];
$url=$google_url."?secret=".$secret."&response=".$recaptcha."&remoteip=".$ip;
$res=getCurlData($url);
$res= json_decode($res, true);
//reCaptcha success check
if($res['success'])
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
if(isset($_POST['submit'])) {
$to = "denislav#svishtov.net";
$subject = "New opinion post";
// data the visitor provided
$name_field = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$phone_field = filter_var($_POST['number']);
$address_field = filter_var($_POST['address'], FILTER_SANITIZE_STRING);
$comment = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
//constructing the message
$body = "
From: $name_field <br/>
Email Address: $address_field <br/>
Phone number: $phone_field <br/>
Message:<br/> $comment ";
// ...and away we go!
mail($to, $subject, $body, $headers);
// redirect to confirmation
header("Location: confirmation2.html");
}
else {
// handle the error somehow
echo "Error accessing the file";
}
}
else
{
echo "Въвели сте грешен код за потвърждаване (reCAPTCHA)! Натиснете "назад" и опитайте отново";
}
}
else
{
echo "Не сте въвели код за потвърждаване (reCAPTCHA)! Натиснете "назад" и опитайте отново";
}
}
?>
worse thing is , it used to work , then I opened it, edited some stuff and now it doesnt work, tried the back-up copy and it still doesnt work !?
Working in CMS MadeSimple. the URLs are correct , the confirmation2.html is a file, not a page made in CMS and it is in the same folder as the php script and if I try to access it directly (not via the contact from) its there, I have tried ' ' and " " quotes, still no change.
Probably a simple mistake, I did try looking for other solutions in here (stackoverflow.com) but nothing to fix my current issue. I know that I shouldnt have any output before the header but... well I dont have any output so, I'm baffled.
Appreciation in advance to those who want to help!
UPDATE:
Seems like the reCAPTCHA was shitting me, and after I removed it - WORKS.
Gonna leave it defenseless for now. Thanks to all who wanted to help.
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";
I've never done that before and simply need a little advice how to do so …
I have a index.php file with a simple contact form.
<form id="contactform" method="post" action="<?php echo $_SERVER["SCRIPT_NAME"] ?>">
The index.php file has the following script on top.
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<?php
//Vars
$Name = Trim(stripslashes($_POST['author']));
$EmailFrom = Trim(stripslashes($_POST['email']));
$Subject = Trim(stripslashes($_POST['subject']));
$Type = Trim(stripslashes($_POST['type']));
$Comment = Trim(stripslashes($_POST['message']));
$EmailTo = "address#something.com";
//Validation
$valid = true;
if ( $Name == "" ) $valid = false;
if ( isValidEmail( $EmailFrom ) == 0 ) $valid = false;
if ($Subject == "") $valid = false;
if ($Comment == "") $valid = false;
function isValidEmail( $email = null ) {
return preg_match( "/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*#[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix", $email );
}
//Body
$Body = $Type;
$Body .= "\n\n";
$Body .= $Comment;
//Headers
$email_header = "From: " . $EmailFrom . "\r\n";
$email_header .= "Content-Type: text/plain; charset=UTF-8\r\n";
$email_header .= "Reply-To: " . $EmailFrom . " \r\n";
//Send
if ($valid)
$success = mail($EmailTo, $Subject, $Body, $email_header);
?>
I have two questions now:
1.)
How exactly can I render/not-render certain stuff when either the validation went wrong or a success or an error comes back when submitting the mail?
e.g. I know that I can do that!
if ( !$valid )
print "Failed to make contact. Enter valid login credentials! <a href='/#contact' title='try again'>try again?</a>";
if ( $success )
print "Successfully made contact.";
else
print "Failed to make contact. <a href='/#contact' title='try again'>try again?</a>"; */
?>
However $valid will always be wrong on page-load when not submitting the form and also the email will always return the error message on the first page load. How can I only render or not render specific stuff when the form is submitted?
E.g. When submitting the form and a success comes back I don't want to render the #contactform anymore. I simply want to print "Successfully made contact" into an h1 or so.
How can I make that happen? It's probably rather simple I just can't find a solution for myself.
2.)
When using $_SERVER["SCRIPT_NAME"] or PHP_SELF as action the url after submitting the form will always change to "mydomain.com/index.php". Can I prevent that from happening? I want to submit the index.php file itself however I just don't like it when /index.php is written into the url. Is it possible to stop that from happening?
Thank you for your help!
Matt,
For the first question as to printing to the screen based on success or failure of the email, your checks seem fine, but you probably aren't going to get an email failure in time to display that to the screen. That said, you just need to wrap your second set of code in an if statement. Something like this:
if( isset($_POST['Submit']) ){ //only attempt to display if form submitted.
//Your code here
}
As for not including the directory in the form action, there are many ways to do this, but here's one:
$scriptString= explode('/',$_SERVER['SCRIPT_NAME']);
$scriptSize = count($scriptString)-1;
$script = $scriptString[$scriptSize];
And then use $script in the form action.
Ok so long story short, I have a simple mailto function I want to apply/run for every name on a db list. Since it's not working, I removed all the mail stuff from it and to test to make sure the while loop was working with the db, did this
<?php
$connect2db = mysqli_connect('127.0.0.1','root','pass','dbnamehere');
if(!$connect2db){
die("Sorry but theres a connection to database error" . mysqli_error);
}
$sn_query = "SELECT * FROM email_list";
$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);
$sn_rowSelect = mysqli_fetch_array($sn_queryResult);
$to = $sn_rowSelect;
?>
<br/><br/>
////lower part on page //////<br/><br/>
<?php
while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {
echo "hello there" . " " . $sn_rowSelect['firstname'] . " <br/>";
}
?>
Now this works, it goess through my db and prints out all my first names from the database list. In my noob brain, id think that if i remove the echo lines, and enter the appropriate mailto information, that it would loop just like before, but send mail to each name. so i did this:
<?php
$sn_query = "SELECT email FROM email_list";
$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);
$sn_rowSelect = mysqli_fetch_array($sn_queryResult);
$to = implode(",",$sn_rowSelect);
$from = $_POST['sender'];
$subject = $_POST['subj'];
$mssg = $_POST['message'];
$headers = "MIME-Version: 1.0rn";
$headers .= "From: $from\r\n";
$mailstatus = mail($to, $subject, $mssg, $headers);
?>
<br/><br/>
//////////<br/><br/>
<?php
while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {
$mailstatus;
if($mailstatus) {
echo "Success";
}else{
echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid\n";
}
}
?>
now this emails the first name on my list, but not the rest.
I don't get any errors so not sure what the problem is. I was going to try an if statement with num_rows but somewhere else, on StackOverflow, someone said that didn't help since the while loop took care of it by itself. (I tried it either way and it still emailed only the first name) I'm trying here but to no avail.
You have not called the mail() function inside your loop. You call it once outside. Instead try something like the following.
Assuming you have retrieved the $to address from your database query (like you did with the firstname in testing), pull it from the rowset, and use it in mail():
while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {
// Get the $to address:
$to = $sn_rowSelect['email'];
// Call mail() inside the loop.
$mailstatus = mail($to, $subject, $mssg, $headers);
if($mailstatus) {
echo "Success";
}else{
echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid\n";
}
}
Note also, that since you call mysql_fetch_array() at the top of your script, your while loop will start with the second row. You should remove the first call to mysql_fetch_array() that occurs before the loop.
$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);
// Don't want this...
//$sn_rowSelect = mysqli_fetch_array($sn_queryResult);