I'm trying to send email using PHP
I have emails.txt with a list of emails and names split by ';'
and I also have content.txt with the email message, for example, "Hello Mr. $name"
I want to send an email, for all users, using content.txt file and alter the $name using the emails.txt to replace the string $name
I built some parts, but I'm stuck
<?php
$file = fopen("emails.txt", "r");
$filecontent = fopen("content.txt", "r");
while(!feof($file)){
$line = fgets($file);
$to = $line;
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:abc#somedomain.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
}
fclose($file);
?>
another part
<?php
$path_to_file = 'content.txt';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("$name","$correctname",$file_contents);
file_put_contents($path_to_file,$file_contents);
?>
Related
I am trying to email piping with cpanel and PHP script. Its working fine. I am looking for get From Address, Subject and Message from received email. My script is like below
#!/usr/bin/php -q
<?php
/*$fd = fopen( "php://stdin", "r" );
$message = "";
while ( !feof( $fd ) )
{
$message .= fread( $fd, 1024 );
}
fclose( $fd );*/
$fd = fopen("php://stdin", "r");
$message = "";
while (!feof($fd)) {
$message .= fread($fd, 1024);
}
fclose($fd);
//split the string into array of strings, each of the string represents a single line, received
$lines = explode("\n", $message);
// initialize variable which will assigned later on
$from = "";
$subject = "";
$headers = "";
$message = "";
$is_header= true;
//loop through each line
for ($i=0; $i < count($lines); $i++) {
if ($is_header) {
// hear information. instead of main message body, all other information are here.
$headers .= $lines[$i]."\n";
// Split out the subject portion
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
//Split out the sender information portion
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
} else {
// content/main message body information
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$is_header = false;
}
}
$to = 'myemail#gmail.com';
$subject = 'the subject';
$message1 = "You have new message from :".$from. "and message is" .$message;
$headers = 'From: webmaster#mydomain.com' . "\r\n" .
'Reply-To: webmaster#mydomain.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message1, $headers);
?>
I am getting result in my email like below
You have new message from :FirstName LastName <senderemail#gmail.com>and message is--00000000000045a1e5059ef97af8
Content-Type: text/plain; charset="UTF-8"
This is Body text Message
--00000000000045a1e5059ef97af8
Content-Type: text/html; charset="UTF-8"
<div dir="ltr"><div class="gmail_default" style="font-family:georgia,serif;font-size:large">This is text<br></div></div>
--00000000000045a1e5059ef97af8--
However its contain unnecessary words in it. I want plain output like below
You have new message from :senderemail#gmail.com and message is This is Body text Message
Sorry I am new in PHP and does not able to solve the issue. Let me know if anyone can help me for extract and get output like this.
Thanks!
The s_name and s_email fields don't show up in the email sent, only the attachments and message show up. Please assist with any changes to the code to show all form fields in the email.
I have looked at a number of posts but can't seem to find the answer to the problem and assistance will be appreciated.
<?php
if($_POST && isset($_FILES['file'])) {
$recepient_email = "recepient#yourmail.com"; //recepient
$from_email = "info#your_domain.com"; //from email using site domain.
$subject = "Attachment email from your website!"; //email subject line
$sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING);
//capture sender name
$sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
$sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
$attachments = $_FILES['file'];
//php validation
if(strlen($sender_name)<4){
die('Name is too short or empty');
}
if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
die('Invalid email');
}
if(strlen($sender_message)<4){
die('Too short message! Please enter something');
}
$file_count = count($attachments['name']); //count total files attached
$boundary = md5("sanwebe.com");
if($file_count > 0){ //if attachment exists
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$sender_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//message text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($sender_message));
//attachments
for ($x = 0; $x < $file_count; $x++) {
if(!empty($attachments['name'][$x])) {
if($attachments['error'][$x]>0) { //exit script and output error if we encounter any
$mymsg = array(
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder"
);
die($mymsg[$attachments['error'][$x]]);
}
//get file info
$file_name = $attachments['name'][$x];
$file_size = $attachments['size'][$x];
$file_type = $attachments['type'][$x];
//read file
$handle = fopen($attachments['tmp_name'][$x], "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=\"$file_name\"\r\n";
$body .="Content-Disposition: attachment; filename=\"$file_name\"\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
}
}
} else { //send plain email otherwise
$headers = "From:".$from_email."\r\n".
"Reply-To: ".$sender_email. "\n" .
"X-Mailer: PHP/" . phpversion();
$body = $sender_message;
}
$sentMail = #mail($recepient_email, $subject, $body, $headers);
if($sentMail) { //output success or failure messages
die('Thank you for your email');
} else {
die('Could not send mail! Please check your PHP mail configuration.');
}
}
?>
Are you able to see all your form fields doing this?
<?php print_r($_POST); ?>
Double-check if all your form fields has the name attr and if their are matching to fields printed above.
$headers .= "Reply-To: ".$sender_email."" . "\r\n";
You have an extra double quote? Should be like this:
$headers .= "Reply-To:" .$sender_email. "\r\n";
Your $sender_name is not used in the email, only when you check if the length is < 4.
I have a emails.txt file with name and email Example: John, john#gmail.com
I can try to export with a different way the emails.txt (for example name: john email: john#gmail.com)
but the important part is
I want to send emails for all recipients that exist in emails.txt using his names to edit the message
$file = fopen("emails.txt", "r") or die("Unable to open file!");
//while(!feof($file)){
$line = fgets($file);
$to = $line;
$subject = "This is subject";
$message = 'Hello Mr %NAME%!';
$header = "From:TESTE \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
fclose($file);
Using explode() to break up the parts of email.txt will give you what you need:
list($name, $to) = explode(",", $line);
$message = sprintf('Hello Mr %s!', $name);
This is based on every row within emails.txt being formatted correctly and clearly such as John Smith, john.smith#example.com
You can also change the code entirely to use str_getcsv() which I will let you look into.
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();
}
?>
I have a problem sending php email using the code below. The MIME heades keep apearing in the message and the attachment appears as scribble text in the mesage body not as attachment. what could be the problem
<?php
session_start();
require_once("includes/functions.php");
require_once("includes/dbconnect.php");
require_once("Mail/mailfunctions.php");
//function_to_be_applied($finaldest_email, $message, $subject, $fromname, $fromemail, $replyto )
function function_to_be_applied($finaldest_email, $key){
//require_once "Mail.php" ;
global $fromemail;
global $message;
global $fromname;
global $subject;
global $replyto;
global $seconds;
global $reprt;
global $headers;
$to = $finaldest_email;
$from = "".$fromname." <$fromemail>";
$subject = $subject;
if(mail($to, $subject, $message, $headers)) {
sleep($seconds);
$reprt .= "Message successfully sent to: ". $to."<br />";
} else {
$reprt .= "Message not successfully sent to: ". $to."<br />";
}
}
if(isset($_POST['submit']))
{
$errors_val = array();
$required_fields = array("subject", "fromemail", "message", "dest_email");
foreach($required_fields as $fieldname)
{
if( !isset($_POST[$fieldname]) || ( empty($_POST[$fieldname]) &&(!is_int($_POST[$fieldname])) ))
{
if($fieldname == "subject")
{$errors_val[0] = "-Sending email without SUBJECT is not allowed";}
if($fieldname == "fromemail")
{$errors_val[1] = "-Sending email without a FROM EMAIL is not allowed";}
if($fieldname == "message")
{$errors_val[2] = "-Sending an empty message is not allow";}
if($fieldname == "dest_email")
{$errors_val[3] = "-There must be at least one email in the destination email address";}
}
}
if(empty($errors_val)){
$errors = array();
if(false == validate_email(trim($_POST['fromemail']))){
$errors[0] = "FROM EMAIL is invalid";
}
if(false == validate_email(trim($_POST['replyto']))){
$errors[1] = "REPLY TO EMAIL is invalid";}
if(!is_numeric(trim($_POST['seconds']))){
$errors[2] = "Seconds between messages must be a number";}
$allowtypes = array("doc", "pdf", "txt", "zip", "gif", "jpeg", "jpg"); //the type of file can be attached
$max_file_size="100"; //describes the size that cab be attached
// checks that we have a file
if((!empty($_FILES["attachment"])) && ($_FILES["attachment"]["error"] == 0)) {
//set a variable $attached = 1
$attached = 1;
// basename -- Returns filename component of path
$filename = basename($_FILES['attachment']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
$filesize=$_FILES['attachment']['size'];
$max_bytes=$max_file_size*1024;
//Check if the file type uploaded is a valid file type.
if (!in_array($ext, $allowtypes)) {
$errors[3]="Invalid extension for your file: <strong>".$filename."</strong>";
unset($attached);
// check the size of each file
} elseif($filesize > $max_bytes) {
$errors[4]= "Your file: <strong>".$filename."</strong> is to big. Max file size is ".$max_file_size."kb.";
unset($attached);
}
}
if(empty($errors)){
//generate a unique boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
if(isset($_POST['seconds']) && ($_POST['seconds'] != ""))
{$seconds = $_POST['seconds'];}else{$seconds = 0.5;}
$subject = trim($_POST['subject']);
$fromname = trim($_POST['fromname']);
$fromemail = trim($_POST['fromemail']);
$from = stripslashes($fromname)."<".stripslashes($fromemail).">";
$emailmessage = trim($_POST['message']);
$replyto = trim($_POST['replyto']);
$dest_email = trim($_POST['dest_email']);
$emailarray = explode("\r\n", $dest_email, 400);
$finaldest_email = array_unique($emailarray );
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To:" . $replyto . "\r\n";
$headers .= "Mime-Version: 1.0\r\n";
$headers .= " Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
//attachment
if(isset($attached)){
$fileatt = $_FILES["attachment"]["tmp_name"];
$fileatt_type = $_FILES["attachment"]["type"];
$fileatt_name = $_FILES["attachment"]["name"];
if (is_uploaded_file($fileatt)) {
// Read the file to be attached ('rb' = read binary)
$data = file_get_contents($fileatt);
//$file = fopen($fileatt,'rb');
//$data = fread($file,filesize($fileatt));
//fclose($file);
// Base64 encode the file data
$finaldata = chunk_split(base64_encode($data));
}
$message = "--{$mime_boundary}\r\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "{$emailmessage}\r\n";
$message .= "--{$mime_boundary}\r\n";
$message .= "Content-Type: {$fileatt_type}; name=\"{$fileatt_name}\"\n\n".
"Content-Transfer-Encoding: base64\n\n";
$message .= "Content-Disposition: attachment; filename=\"{$fileatt_name}\"\n\n";
$message .= "{$finaldata} \r\n--{$mime_boundary}--\r\n";
}elseif(!isset($attached)){
$message = "--{$mime_boundary}\r\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\" \r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "{$emailmessage}\r\n";
$message .= "--{$mime_boundary}--\r\n";
}
$reprt = "Preparing to send message..<br />";
if( true == array_walk($finaldest_email, 'function_to_be_applied' )){
$numberofemailsent = count($finaldest_email);
}else{echo "No email sent";}
}else{$string = implode("<br /> -" , $errors); $error_message = $string; }
}else{$string = implode("<br /> -" , $errors_val); $error_message = $string; }
}
?>
Don't generate your own mime emails. Use PHPMailer or Swiftmailer and reduce a huge chunk of that script down to maybe 10 lines of code.
As well, don't verify file types by looking at filenames. It's trivial to forge a filename AND the client-specified mime type. Always use server-side mime verification instead.