mail() is Incorrectly Sending Emails to cPanel Default Account - php

I purchased a domain from GoDaddy and linked it to Office 365 (via MX records). This means I have several email accounts in Outlook that are #mydomain.com.
Example Outlook accounts:
sales#mydomain.com
contact#mydomain.com
matt#mydomain.com
I can send/receive emails through those accounts.
My website is hosted on basic web hosting with a cPanel installation, which means I was given a "default" email account. For example: default#mydomain.com. I wrote a PHP script on my website (contact form) that sends emails via mail() to contact#mydomain.com.
However all the emails are sent to the default cPanel account default#mydomain.com instead of the Outlook account contact#mydomain.com.
To test, I tried sending the emails to my personal account that is not hosted on mydomain and it works as expected. Emails are sent instantly.
How come my website incorrectly send emails to the Outlook accounts? Thanks for your time.
EDIT:
The script was requested:
<?php
$uploadedFile = $statusMsg = '';
if (isset($_POST['submit']))
{
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
if(!empty($first_name) && !empty($last_name) && !empty($message))
{
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
$uploadStatus = 1;
if(!empty($_FILES["attach"]["name"]))
{
$targetDir = "uploads/";
$fileName = basename($_FILES["attach"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["attach"]["tmp_name"], $targetFilePath))
{
$uploadedFile = $targetFilePath;
}
else
{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}
if($uploadStatus == 1)
{
$name = $first_name.' '.$last_name;
$mailTo = "contact#mydomain.com";//changed to my real outlook account
$htmlContent = '<h2>Contact Request Submitted</h2>
<p><b>Name:</b> '.$name.'</p>
<p><b>Email:</b> '.$email.'</p>
<p><b>Phone:</b> '.$phone.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $name"." <".$email.">";
if(!empty($uploadedFile) && file_exists($uploadedFile))
{
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $email;
// Send email
$mail = mail($mailTo, "Contact Form Submission from ".$name, $message, $headers, $returnpath);
// Delete attachment file from the server
#unlink($uploadedFile);
}
else
{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($mailTo, 'Contact Form Submission from '.$name, $htmlContent, $headers);
}
// If mail sent
if($mail)
{
$statusMsg = "Your message has been sent. Thanks!";
}
else
{
$statusMsg = 'Your contact request submission failed, please try again.';
}
}
}
else
{
$statusMsg = 'Please enter a valid email address.';
}
}
else
{
$statusMsg = "Please fill out the required information.";
}
}
?>

The solution was to change my cPanel "Email Routing" option to "Remote" in order for all local emails to first check with the MX records.

Related

Unable to display error or Success msg in php Contact form code

This is my Code,
i am not getting an error or success msg display after form submission. Rest all code is working fine I am getting mail with attachment, but want to display if the mail sent successfully or fail. as an error on form page...
i am not getting an error or success msg display after form submission. Rest all code is working fine I am getting mail with attachment, but want to display if the mail sent successfully or fail. as an error on form page...
<p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>
<?php
require 'include/config.php';
$postData = $uploadedFile = $echo = '';
$msgClass = 'errordiv';
if(isset($_POST['submit'])){
// Get the submitted form data
$postData = $_POST;
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['phone2'];
$message = $_POST['applyfor'];
// Check whether submitted data is not empty
if(!empty($email) && !empty($name) && !empty($subject) && !empty($message)){
// Validate email
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$echo = 'Please enter your valid email.';
}else{
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = "resumes/";
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, there was an error uploading your file.';
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = $receiverEmail;
// Sender
$from = '';
$fromName = '';
// Subject
$emailSubject = 'Resume Submitted by '.$name;
// Message
$htmlContent ='';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $email;
$secretKey = $secretkey;
$captcha=$_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$headers2 .= $company_mail;
$headers2 .= 'MIME-Version: 1.0' . "\r\n";
$headers2 .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if($responseKeys["success"]) {
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
#unlink($uploadedFile);
}else{
$statusMsg = 'Clear the Captcha';
}
}
}
}
}
// If mail sent
if($mail){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'succdiv';
$postData = '';
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
}
}
?>```
require 'include/config.php';
$postData = $uploadedFile = $echo = '';
$msgClass = 'errordiv';
if(isset($_POST['submit'])){
// Get the submitted form data
$postData = $_POST;
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['phone2'];
$message = $_POST['applyfor'];
// Check whether submitted data is not empty
if(!empty($email) && !empty($name) && !empty($subject) && !empty($message)){
// Validate email
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$echo = 'Please enter your valid email.';
}else{
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = "resumes/";
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, there was an error uploading your file.';
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = $receiverEmail;
// Sender
$from = '';
$fromName = '';
// Subject
$emailSubject = 'Resume Submitted by '.$name;
// Message
$htmlContent ='';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $email;
$secretKey = $secretkey;
$captcha=$_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$headers2 .= $company_mail;
$headers2 .= 'MIME-Version: 1.0' . "\r\n";
$headers2 .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if($responseKeys["success"]) {
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
#unlink($uploadedFile);
}else{
$statusMsg = 'Clear the Captcha';
}
}
}
}
}
// If mail sent
if($mail){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'succdiv';
$postData = '';
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
}
}
Write HTML code below PHP code. As $statusMsg variable value set in PHP code.
<p class="statusMsg <?php echo !empty($msgClass)?$msgClass:''; ?>"><?php echo $statusMsg; ?></p>

PHP Email script to send emails with attachment not sending video files [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I found a script from codexworld to send an email with an attachment using PHP. I did edit it slightly as I needed to add a few more inputs, but it works with one exception, it won't send video files. I will send picture and document files, but no video. I keep getting the status message: "Your contact request submission failed, please try again."
Can anyone look at this code and tell me why this is happening and how to fix it?
<?php
$postData = $uploadedFile = $statusMsg = '';
$msgClass = 'errordiv';
if(isset($_POST['submit'])){
// Get the submitted form data
$postData = $_POST;
$email = $_POST['email'];
$name = $_POST['name'];
$category = $_POST['category'];
$location=$_POST['location'];
$URL = $_POST['URL'];
$message = $_POST['message'];
$hauntname = $_POST['hauntname'];
// Check whether submitted data is not empty
if(!empty($email) && !empty($name) && !empty($message)){
// Validate email
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$statusMsg = 'Please enter your valid email.';
}else{
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = "uploads/";
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('m4p', 'mp4', 'jpg', 'png', 'jpeg', 'mov');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.\r\n";
}
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, only image or video files are allowed to be uploaded.\r\n";
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = 'submission#hyhpawardshow.com';
// Sender
$from = $email;
$fromName = $name;
// Subject
$emailSubject = $category.' submission from '.$name;
// Message
$htmlContent = '<h2>Submission</h2>
<p><b>Name:</b> '.$name.'</p>
<p><b>Haunt Name:</b> '.$hauntname.'</p>
<p><b>Location:</b> '.$location.'</p>
<p><b>Email:</b> '.$email.'</p>
<p><b>Category:</b> '.$category.'</p>
<p><b>URL:</b> '.$URL.'</p>
<p><b>Message:</b><br/>'.$message.'</p>';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($uploadedFile,"rb");
$data = #fread($fp,filesize($uploadedFile));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $email;
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
// Delete attachment file from the server
#unlink($uploadedFile);
}else{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
}
// If mail sent
if($mail){
$statusMsg = "Your contact request has been submitted successfully !\r\n";
$msgClass = 'succdiv';
$postData = '';
}else{
$statusMsg = "Your contact request submission failed, please try again.\r\n";
}
}
}
}else{
$statusMsg = 'Please fill all the fields.';
}
}
?>
So, as it turns out, it was not my code at all, but the mail server. The max file size is messed up and that is what was causing it to fail. I'm currently working with my hosting tech support to have this resolved.
Thank you all to tried to help. I truly appreciate it.

multiple files as attachment from a form and send a email

Following is the code I am using to send multiple files as attachment in a mail, tested it in local environment, the attachments were reaching the mail box but as empty files, and in live environment, result is mail could not be sent, though files get saved in the upload folder on the server...a newbie in php so please can anyone help what am I doing wrong..??
In local environment i was using this code $server_file = "/localhost:81/xyz/uploads/$path_parts[basename]"; in place what is mentioned down there under move this file to the server
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//did files get sent
if(isset($_FILES) && (bool) $_FILES) {
//define allowed extensions
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
$username=$_POST['username'];
$email=$_POST['email'];
//loop through all the files
foreach($_FILES as $name=>$file){
//define some variables
$file_name= $file['name'];
$temp_name= $file['tmp_name'];
//check if this file type is allowed
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("extension not allowed");
}
//move this file to the server
$server_file = "/home/public_html/xyz.com/uploads/$path_parts[basename]";
move_uploaded_file($temp_name,$server_file);
//add this file to array of files
array_push($files,$server_file);
}
//define some mail variables
$to = "info#xyz.com";
$from = "From: $username<$email>\r\nReturn-path: $email";
$subject = "Photo attachment of . $name .";
$msg = "Images of $username, $email";
$headers = "From: $from";
//define our boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//tell the header about the boundary
$headers .= "nMIME-Version:1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
//part1: define the plain text email
$message = "\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n". $msg ."\n\n";
$message .="--{$mime_boundary}\n";
//part2: loop and define mail attachments
foreach($files as $file){
$aFile = fopen($file,"rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .="Content-Type: {\"application/octet-stream\"};\n";
$message .= " name=\"$files\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$files\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
//send the email
$ok = mail($to, $subject, $message, $headers, $from);
if($ok){
header("Location: thank-your.php");
}
else{
echo"<p>mail could not be sent!</p>";
}
die();
}
?>

PHP Order Form - Email with Attachment

I am trying to create an order form which when complete, passes you on to the order.php page (sends the email), where you are then passed on to paypal. Everything was working fine until i tried to add attachments, when i added the code for attachment, the email is no longer sent.
<?php
$to = 'hidden' ;
$from = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$headers = "From: $from";
$subject = "Distinctive Writers - Contact Form";
$tprice = $_REQUEST['tprice'] ;
$fields = array();
$fields{"name"} = "name";
$fields{"email"} = "email";
$fields{"number"} = "number";
$fields{"subject"} = "subject";
$fields{"doctype"} = "doctype";
$fields{"spec"} = "spec";
$fields{"grade"} = "grade";
$fields{"days"} = "days";
$fields{"due"} = "due";
$fields{"pages"} = "pages";
$fields{"price"} = "price";
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
$tmp_name = $_FILES['filename']['tmp_name'];
$type = $_FILES['filename']['type'];
$file_name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
if (file_exists($tmp_name)){
// Check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// Now Open the file for a binary read
$file = fopen($tmp_name,'rb');
// Now read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// Now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// Now we'll insert a boundary to indicate we're starting the attachment we have to specify the content type, file name, and disposition as an attachment, then add the file content and set another boundary to indicate that the end of the file has been reached
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$file_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
$body = "We have received the following information:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$headers2 = "From: noreply#YourCompany.com";
$subject2 = "Thank you for contacting us";
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.oursite.com";
if($from == '') {print "You have not entered an email, please go back and try again";}
else {
if($name == '') {print "You have not entered a name, please go back and try again";}
else {
$send = mail($to, $subject, $body, $headers, $message);
$send2 = mail($from, $subject2, $autoreply, $headers2);
}
}
if(!mail($to, $subject, $body, $headers, $message)){
print "ERROR!!";
}
}
?>
I recommend PHPMailer too as mentioned by pc-shooter
then you can use
$mail = new PHPMailer();
then you can utilize either one of these two
$mail->AddStringAttachment($string,$filename)
$mail->AddAttachment($path);
Something to keep in mind, something else might be blocking the email. if the mail function returns TRUE then the mail was dispatched.

test PHP mail()

I have a mail submission script that is working exactly as expected on both a dev environment and live with one exception. I am getting conflicting results from the mail() test conditional on the live environment vs the dev environment.
On my dev environment it redirects to $ThanksURL on success. On the live server even through the mail is successfully the script proceeds to the else statement and redirects back to the form page.
This has been driving me crazy so any ideas as to why would be most welcome.
Snippet of the issue:
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){ header("Location: $ThanksURL");
exit;
}else{ $_SESSION['error'] .= " There has been a problems submitting your details. <br />";
header("Location: $form");
exit;
}// end if ok
Script in full:
<?php
session_start();
$form = 'index.php';
$_SESSION['error'] = "The following errors have occured: ";
if(isset($_POST['submitted'])) {
// email fields: to, from, subject, and so on
// Here
$from = "Form Feedback <******#gmail.com>";
$to = "******#gmail.com";
$subject = "Competition";
$ThanksURL = "thankyou.html";
$headers = "From: $from";
$returnpath = "-f" . $from;
$attachment = 0; // is there an attachement
//form fields
$emailAddress = stripslashes($_POST['email']);
$phone = stripslashes($_POST['phone']);
$comments = stripslashes($_POST['comments']);
//basic message info
$message = "Info submitted:\n\nEmail address: " .$emailAddress ."\n\nPhone number: " .$phone."\n\nComments:\n ".$comments. "\n\n";
if($_FILES['attachment']['error'] == 4) {
$message .="No attachement included";
}else{
// test file type and size for submission
$allowedExts = array("doc", "docx", "pdf", "txt");
$extension = end(explode(".", $_FILES['attachment']["name"]));
if ((($_FILES['attachment']["type"] == "application/msword")
|| ($_FILES['attachment']["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")//docx mime
|| ($_FILES['attachment']["type"] == "application/pdf")
|| ($_FILES['attachment']["type"] == "application/plain")
|| ($_FILES['attachment']["type"] == "text/plain"))
&& ($_FILES['attachment']["size"] < 2097152 )
&& in_array($extension, $allowedExts)){
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n"."Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// prepare the files uplaod
$message .= "--{$mime_boundary}\n";
$fp = #fopen($_FILES['attachment']['tmp_name'],"rb");
$data = #fread($fp,filesize($_FILES['attachment']['tmp_name']));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".$_FILES['attachment']['name']."\"\n"."Content-Description: ".$_FILES['attachment']['name']."\n" ."Content-Disposition: attachment;\n" . " filename=\"".$_FILES['attachment']['name']."\";size=".$_FILES['attachment']['size'].";\n"."Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}--";
}else{
$_SESSION['error'] .= "Error: " . $_FILES["attachment"]["name"] . " is not a doc, docx, pdf or txt file or is larger than 2mb. Please resubmit <br />";
header("Location: $form");
exit;
}
}//file conditional
//prepare mail
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){
header("Location: $ThanksURL");
exit;
}else{
$_SESSION['error'] .= " There has been a problems submitting your details. <br />";
header("Location: $form");
exit;
}// end if ok
}// end sub
?>
Sorry to say this, but php mail can return something else on success than true or false, like mentioned in the php manual comment. Also, it is known to return false on success on some situations, too.
PHP mail() is a kludgy function from many different angles, and personally I would advise against using it in production systems. There are quite a few alternatives, such as swift mailer, PHP mailer, Zend_Mail etc.
However, if you want to use it, you should definitely log the actions and in this case, return values, and not have # to hide your return values.
As a summary, in this case mail() returned an empty string, and not true or false.

Categories