i am trying to send emails via Bcc and i was expecting that they were hidden but it seems not. Maybe my code is not correct?
// grab all emails from txt file
$myfile = fopen("database-email.txt", "r") or die("Unable to open file!");
$allEmails = fread($myfile,filesize("database-email.txt"));
fclose($myfile);
$afzender = "noreply#wisselslag.nl";
$to = 'pj.maessen41#live.nl';
$subject = 'Nieuwsbrief de Wisselslag';
$headers = "From: " . $afzender . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: " . $allEmails . "\r\n";
if (mail($to, $subject, $message, $headers)) {
echo 'Bericht is verstuurd!';
} else {
echo 'There was a problem sending the email.';
}
So i have a database-email.txt file in which all the emails are stored, comma seperated from each other like this:
joey.tims#gmail.com,
j.maessen#online.nl,
john.doe#live.nl,
diana.johnson#hotmail.com,
When sending to my gmail account, i can see this:
How is this possible that i can see to where the email also is sent to?
The email list should not have new line character.
Make it one line:
$allEmails = str_replace(array("\n","\r"), '', $allEmails);
// joey.tims#gmail.com, j.maessen#online.nl, john.doe#live.nl, diana.johnson#hotmail.com
As mentioned in my comment, any list of recipients should not contain newline characters.
I'd change the format of your file to a single line
joey.tims#gmail.com,j.maessen#online.nl,john.doe#live.nl,diana.johnson#hotmail.com
I'd also use file_get_contents() instead of fopen / fread.
Alternately, store your email addresses on each line, without commas, eg
joey.tims#gmail.com
j.maessen#online.nl
john.doe#live.nl
diana.johnson#hotmail.com
and use file() and implode()
$allEmails = implode(',' file(__DIR__ . '/database-email.txt',
FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
Related
My code reads the line (email message) from a comma delimited file and sends out the email. it works well, i used \r\n\ for the new line however when it sends out the mail , the user receivers \r\n\ instead of a new line..
in the emailmessages.csv it would read
"from","to","subject","message"
"from#example.com","to#example.com","the subject","message is this new line \r\n endline"
PHP: code
$filename = "emailmessages.csv";
$csvArray = ImportCSV2Array($filename);
foreach ($csvArray as $row) {
$to = $row['to'];
$from = $row['from'];
$subject = $row['subject'];
$message = $row['message'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1" . "\r\n";
$headers .= "From: $from" . "\r\n";
mail($to, $subject, $message, $headers);
}
Could the explode command help me (explode $message ?)
i found the answer
$message = str_replace('\r\n', "\r\n", $message);
Email rendered as HTML most of times, so use <br/> instead of \r\n:
"from#example.com","to#example.com","the subject","message is this new line <br/> endline"
I have the following function for sending an email:
function send_email($email){
$subject = "TITLE";
$message = "HERE IS THE MESSAGE";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: <emaily>' . "\r\n";
mail($email,$subject,$message,$headers);
}
Instead of $message being a string, I want to call in the file email.html which holds my template.
I have added this:
require 'email.html';
But how can I call in the file?
$message = [call in email.html here]
Require is used when you want to call functions within another php file, or when you want to include some data to an HTTP response.
For this problem, file_get_contents('email.html') is the preferred option. This would be the method I would use:
function send_email($email){
$subject = "Subject of your email";
$message = "";
if(file_exists("email_template.html")){
$message = file_get_contents('email_template.html');
$parts_to_mod = array("part1", "part2");
$replace_with = array($value1, $value2);
for($i=0; $i<count($parts_to_mod); $i++){
$message = str_replace($parts_to_mod[$i], $replace_with[$i], $message);
}
}else{
$message = "Some Default Message";
/* this likely won't ever be called, but it's good to have error handling */
}
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: <doNotReply#myDomain.com>' . "\r\n";
$headers .= "To: <$email>\r\n";
$header .= "Reply-To: doNotReply#myDomain.com\r\n";
mail($email,$subject,$message,$headers);
}
I modified your code a little bit and added in both the file_get_contents and file_exists. file_exists confirms that the file is there. If it's not, it avoids the potential error from trying to read it in and can be changed to use some default. My next addition was a for loop. In the $parts_to_mod array, enter in the default values from the template that need to be replaced. In the $replace_with array, put in the unique values that you want to replace parts of the template with.
As an example where I use this, I have a template URL for one of my programs that says id=IDENTIFIER&hash=THEHASH so in my program, my parts_to_mod says $parts_to_mod = array("IDENTIFIER", "THEHASH"); and my replace_with says $replace_with = array($theUsersIdentifier, $theUsersHash);. It then enters the for-loop and replaces the those values in parts_to_modify with the values in replace_with.
Simple concepts and they make your code much shorter and easier to maintain.
Edit:
Here is some sample code:
Let's the say the template is:
<span>Dear PUTNAMEHERE,</span><br>
<div>PUTMESSAGEHERE</div>
<div>Sincerely,<br>PUTSENDERHERE</div>
So, in your php code you'd say:
$parts_to_mod = array("PUTNAMEHERE", "PUTMESSAGEHERE", "PUTSENDERHERE");
$replace_with = array($name, $theBodyOfYourEmail, $whoYouAre);
just use file_get_contents('email.html') This method returns a string with the file contents
You can use this function to call custom email template.
function email($fields = array(),$name_file, $from, $to) {
if(!empty($name_file)) {
$mail_tem_path = 'templates/mails/mail--'.$name_file.'.php'; //change path of files and type file.
if(file_exists($mail_tem_path)) {
$headers = "MIME-Version: 1.0". "\r\n";
$headers .= "Content-Type: text/html;charset=UTF-8". "\r\n";
// Additional headers
$headers .= "From:".$fields["subject_from"]." <$from>". "\r\n";
$headers .= "Content-Transfer-Encoding: 8Bit". "\r\n";
$message = file_get_contents($mail_tem_path);
$message = preg_replace("/\"/", "'", $message);
foreach ($fields as $field) {
// Replace the % with the actual information
$message = str_replace('%'.$field["name"].'%', $field["value"], $message);
}
$send = mail($to, $fields["subject"], $message, $headers);
} else {
$send = mail($to, "Error read mail template", "Contact with admin to repair this action.");
}
} else {
$send = mail($to, "Error no exist mail template", "Contact with admin to repair this action.");
}
return $send;
}
Template html
<html>
<body>
TODO write content %value_on_array%
</body>
</html>
Array and execute function.
$fields = array(
"subject" => "tienda_seller_subject",
"subject_from" => "tienda_email_subject_from",
0 => array(
"name" => "value_on_array",
"value" => "result before change"
),
);
//email($fields = array(),$name_file, $from, $to);
email($fields, 'admin', 'owner#email.com', 'client#email.com');
Result
I have a script that recognizes the level and I have added alerts to let me know if I have passed through the code. The two email addresses are reflecting. I want to send out two emails seperately, but my inbox is not working. I have checked my junk mail.
Is there something that am i missing?
function emaillog($to,$id,$subject,$message){
include("dbconnect.php");
mysql_query("INSERT INTO emlog(mm,tt,ss,rr) VALUES('$message','$to','$subject','$id')");
}
if($level == 1){
$assignedtowho_email_result = mysql_query("SELECT Email FROM sheet1 WHERE id IN(SELECT assignedtowho FROM tbl_one WHERE id =$id)");
while($row_email=mysql_fetch_array($assignedtowho_email_result)){
$assignedtowho_email=$row_email['Email'];
}
// Email Sending department
$to = $senderEmail;
$subject = "Refferal status updated by recieving r";
$message = "Your status has been updated by ";
$from = "info#test.co.za";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
emaillog($to,$id,$subject,$message);
$message_alert="Sender mail sent: ".$to;
echo '<script>alert("'.$message_alert.'")</script>';
//echo "Mail Sent.";
// Email Recieving department
$to = $assignedtowho_email;
$subject = "Refferal status updated ";
$message = "Your refferal status has been updated";
$from = "info#test.co.za";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
emaillog($to,$id,$subject,$message);
$message_alert_2="Assigned mail sent: ".$to;
echo '<script>alert("'.$message_alert_2.'")</script>';
//echo "Mail Sent.";
}
Requirements
For the Mail functions to be available, PHP must have access to the sendmail binary on your system during compile time. If you use another mail program, such as qmail or postfix, be sure to use the appropriate sendmail wrappers that come with them. PHP will first look for sendmail in your PATH, and then in the following: /usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib. It's highly recommended to have sendmail available from your PATH. Also, the user that compiled PHP must have permission to access the sendmail binary.
http://tr2.php.net/manual/en/mail.requirements.php
Be sure you have all requirements and SMTP server.
Therefore, mail() function prop. can change depends on your OS and PHP version
You can see all of this [here][1]
in ChangeLog side.
If you are using Windows , you must use PEAR Mail . İt's here
For Linux OS such as Ubuntu and Centos , you must be sure configure php.ini and apache/httpd.ini
You use this for on every OS
<?php # Is the OS Windows or Mac or Linux
if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
$eol="\r\n";
} elseif (strtoupper(substr(PHP_OS,0,3)=='MAC')) {
$eol="\r";
} else {
$eol="\n";
} ?>
<?php
# File for Attachment
$f_name="../../letters/".$letter; // use relative path OR ELSE big headaches. $letter is my file for attaching.
$handle=fopen($f_name, 'rb');
$f_contents=fread($handle, filesize($f_name));
$f_contents=chunk_split(base64_encode($f_contents)); //Encode The Data For Transition using base64_encode();
$f_type=filetype($f_name);
fclose($handle);
# To Email Address
$emailaddress="user#example.com";
# Message Subject
$emailsubject="Heres An Email with a PDF".date("Y/m/d H:i:s");
# Message Body
ob_start();
require("emailbody.php"); // i made a simple & pretty page for showing in the email
$body=ob_get_contents(); ob_end_clean();
# Common Headers
$headers .= 'From: Jonny <jon#example.com>'.$eol;
$headers .= 'Reply-To: Jonny <jon#example.com>'.$eol;
$headers .= 'Return-Path: Jonny <jon#example.com>'.$eol; // these two to set reply address
$headers .= "Message-ID:<".$now." TheSystem#".$_SERVER['SERVER_NAME'].">".$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol; // These two to help avoid spam-filters
# Boundry for marking the split & Multitype Headers
$mime_boundary=md5(time());
$headers .= 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
$msg = "";
# Attachment
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: application/pdf; name=\"".$letter."\"".$eol; // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
$msg .= "Content-Transfer-Encoding: base64".$eol;
$msg .= "Content-Disposition: attachment; filename=\"".$letter."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
$msg .= $f_contents.$eol.$eol;
# Setup for text OR html
$msg .= "Content-Type: multipart/alternative".$eol;
# Text Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= "This is a multi-part message in MIME format.".$eol;
$msg .= "If you are reading this, please update your email-reading-software.".$eol;
$msg .= "+ + Text Only Email from Genius Jon + +".$eol.$eol;
# HTML Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= $body.$eol.$eol;
# Finished
$msg .= "--".$mime_boundary."--".$eol.$eol; // finish with two eol's for better security. see Injection.
# SEND THE EMAIL
ini_set(sendmail_from,'from#example.com'); // the INI lines are to force the From Address to be used !
mail($emailaddress, $emailsubject, $msg, $headers);
ini_restore(sendmail_from);
?>
I have a PHP script which sends an e-card to multiple recipients in function calls (takes an array of comma-separated email addresses and mail()s to each one individually). However, when looking at the received email, each client can see the other addresses that the email was sent to, making me believe they are all being sent in one email, despite the separate mail() calls. Here is my current code:
<?php
$headers = "From: ".$_POST['email']."\r\n";
$headers .= "Content-type: text/html\r\n";
$array=explode(",", $_POST['sendto']);
for ($i = 0; $i < count($array); ++$i) {
mail(trim($array[$i]), "Happy Holidays!", $body, $headers);
}
?>
How do I fix this so that the recipient can only see their email address in the "to" field?
Thanks!
What you want to use is the BCC field.
https://en.wikipedia.org/wiki/Blind_carbon_copy
Code:
<?php
$_POST['email'] = str_replace(array("\n", "\r"), '', $_POST['email']);
$_POST['sendto'] = str_replace(array("\n", "\r"), '', $_POST['sendto']);
$headers = "From: " . $_POST['email'] . "\r\n"
. "Content-Type: text/html\r\n"
. "BCC: " . $_POST['sendto'] . "\r\n";
mail($_POST['email'], 'Happy Holidays!', $body, $headers);
?>
Send the email to the sender, but BCC the recipients. Also I removed \r and \n chars from the BCC and FROM field otherwise will allow mail header injection attack. Make sure to do the same to $body.
I use PHP script to send email with multiple attachments, it works great for gmail, but in Microsoft Outlook i also see blank file ATT00010.txt (random numbers.) as attachment. And when i send email from outlook with multiple attachments as well it does not show no file like this.
I echo'ed output from email script and there is no such file in code. Can someone tell me how to remove this file from outlook?
Email script is below.
// array with filenames to be sent as attachment
$files = array("file_1.ext","file_2.ext","file_3.ext",......);
// email fields: to, from, subject, and so on
$to = "mail#mail.com";
$from = "mail#mail.com";
$subject ="My subject";
$message = "My message";
$headers = "From: $from";
// 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 = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
If you want something that's a little less of a pain to use and send attachments with, try Swift Mailer. (swiftmailer.org) I've been using it in my projects and it works great.
Here's an example:
$message = Swift_Message::newInstance()
->setSubject('Webinar Registration')
->setFrom(array('replyto#example.org' => 'From Name'))
->setTo(array('destination#example.org'))
->setBody($MESSAGE_TEXT)
;
$message->attach(Swift_Attachment::fromPath('SOME_FILE_PATH'));
$transport = Swift_SmtpTransport::newInstance('127.0.0.1', 25);
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($message);
Just my two cents.
Otherwise, I was going to mention what someone else already beat me to -- check the boundaries.
The last boundary line in a multipart/* message must have -- appended at the end, in addition to what all of the other boundary lines have. A consumer can use that to recognize the end of a message.
Apparently Outlook treats the absence of the correct ending as an indication that the message has been truncated, and then does the best it can to display whatever it did receive.
Its my second account, i actually found solution and don't need no library or class at all although i might turn this into class and add some stuff, its always better to have full understanding of process not just from, to, files etc fields.
Solution is simple here just replace last part with
if ($x == count($files)-1)
$message .= "--{$mime_boundary}--\r\n";
else
$message .= "--{$mime_boundary}\n";
\r is not necessary
if you just put -- it will use it many times inside loop IF checks if this is last loop.