How to send multiple attachment in single mail in php - php

I would like to know about attaching multiple attachment in single mail and send . Please refer my following oode. In this only one file is getting attached. That is second file. First file is not at all considering for attaching. But file is being created properly in the path specified.
$filename=array($filenamee1 ,$filenamee2);
for($x=0;$x<count($filename);$x++){
echo $path.$filename[$x];
$file = $path.$filename[$x];
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "cc: ".$mailtoCC."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename[$x]."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename[$x]."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
}
if (mail($mailto, $subject, "", $header)) {
echo "<br>mail sent Successfully... OK";
} else {
echo "<br>mail send ... ERROR!";
}

Following the reusability principles, you can use https://github.com/PHPMailer/PHPMailer
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'jswan'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'from#example.com';
$mail->FromName = 'Mailer';
$mail->addAddress('josh#example.net', 'Josh Adams'); // Add a recipient
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
Source: How to attach two or multiple files and send mail in PHP

This is what I came up with for multiple files with form file name userfile:
for($ct=0;$ct<count($_FILES['userfile']['tmp_name']);$ct++)
{
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name'][$ct]));
$filename =$_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $uploadfile)) {
$mail->addAttachment($uploadfile, $filename);
}
}
if ($mail->send()) {
echo "Sent";
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}

For those who want to send multiple files using phpMailer and input file multiple.
I joined and used the above two codes of #Rishi and #Matheno to achieve this result that dinamically add attachments selecteds by user.
On your input file name remember to put brackets:
<input type="file" multiple="multiple" name="attach_file[]" />
On your php send file:
Instead of:
$mail->addAttachment('/var/tmp/file.tar.gz');
Use:
for($ct=0;$ct<count($_FILES['attach_file']['tmp_name']);$ct++){
$mail->AddAttachment($_FILES['attach_file']['tmp_name'][$ct],$_FILES['attach_file']['name'][$ct]);
}

Related

Attachment collecting only one file instead of multiple in php mail

for upload files;
if($_FILES['photo']['name']!=""){
$target_path_folder = "career/";
$img_name = time() . rand(11, 99) . basename( $_FILES['photo']['name']);
$target_path = $target_path_folder .$img_name;
move_uploaded_file($_FILES['photo']['tmp_name'], $target_path);}
for upload second file
if($_FILES['resume']['name']!=""){
$target_path_folderr = "career/";
$resume_name = time() . rand(11, 99) . basename( $_FILES['resume']['name']);
$target_pathr = $target_path_folderr .$resume_name;
move_uploaded_file($_FILES['resume']['tmp_name'], $target_pathr);}
For Send Mail
$files = array($img_name, $resume_name);
$to = "info#mydomain.com";
$from = "info#mydomain.com";
$subject ="My subject";
$message = $msg;
$headers = "From: $from";
$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-Type: text/plain; charset=utf-8\r\n";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . "
boundary=\"{$mime_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";
for($x=0;$x<count($files);$x++){
$filesloc="home/myroot/career/".$files[$x];
$file = fopen($filesloc,"rb");
$data = fread($file,filesize($filesloc));
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";}
$success = #mail($to, $subject, $message, $headers);
if ($success) {
$_SESSION['career'] = "Thankyou!! We will contact you soon.";
} else {
$_SESSION['career'] = "Erorr!! Please try again.";}
There is picking only one file the first one from $files array and not sending email also please help me to solve the issue
Using mail() for sending an email is a bad idea. This function isn't always working. Try PHPMailer.
Sample code :
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
//Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
You can modify the above code according to your needs. You can even attach more than one file.

How to attach pdf in mail of html content in mail on form submit using php?

I want to attach a pdf file of html content when form submit.
Html form is made with css so pdf is generated with css.
generated pdf has attached in mail on form submit.
you can use this function to send email. I hope you have created file to attach so you can pass file name i fuction.
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
// Messages for testing only, nobody will see them unless this script URL is visited manually
if (mail($mailto, $subject, "", $header)) {
echo "Message sent!";
} else {
echo "ERROR sending message.";
}
}
If you are using phpmailer fuction so this code will help you to send pdf file:
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.server.net";
$mail->SMTPAuth = true;
$mail->Username = "username#domain.com";
$mail->Password = "password1";
$mail->From = "username#domain.com";
$mail->FromName = "Software something";
$mail->AddAddress("targetguy#domain.com", "Target Guy");
$mail->AddReplyTo("username#domain.com", "Software Simian");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = "Subject";
$mail->Body = "Message";
$mail->AltBody = strip_tags("Message:);
$mail->AddAttachment("filename.pdf");
if(!$mail->Send()){
$resultstatus = 'Failed';
}

php email function not sending attachment

I am trying to send a email with attachment my code is below let me know if i am doing missing something or doing something wrong
<?php
function mail_attachment( $filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message ) {
$file = $path. "/" .$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$separator = md5(uniqid(time()));
$eol = PHP_EOL;
$header = "From: ".$from_name." <usman_86#rocketmail.com>".$from_mail. $eol;
$header .= "Reply-To: ".$replyto.$eol;
$header .= "MIME-Version: 1.0".$eol;
$header .= "Content-Type: multipart/mixed; boundary=\"".$separator. "\"" . $eol . $eol;
$header .= "Content-Transfer-Encoding: 7bit" . $eol;
$header .= "--".$separator. $eol;
$header .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$header .= "Content-Transfer-Encoding: 8bit" . $eol . $eol;
$header .= $message. $eol . $eol;
$header .= "--".$separator. $eol;
$header .= "Content-Type: application/octet-stream; name=\"".$filename. $eol; // use different content types here
$header .= "Content-Transfer-Encoding: base64".$eol;
$header .= "Content-Disposition: attachment; filename=\"".$filename. $eol;
$header .= $content. $eol;
$header .= "--".$separator."--";
ob_start(); //Turn on output buffering
if( mail( $mailto, $subject, "", $header ) ) {
echo "mail send ... OK"; // or use booleans here
} else {
echo "mail send ... ERROR!";
}
}
if( isset($_REQUEST['FindDealer']) ){
$my_file = "pdf.pdf";
$my_path = "/";
$my_name = " Find Dealer # flowsleeve";
$my_mail = "stifstone#gmail.com";
$my_replyto = "my_reply_to#flowsleeve.com";
$my_subject = "Find Dealer # flowsleeve";
$my_message = "Hallo,\r\ndoPlease find Attached PDF For Dealers";
mail_attachment( $my_file, $my_path, $my_mail, $my_name, $my_replyto, $my_subject, $my_message );
header("Location: index.php#section8");
exit();
}
?>
use $mail->addAttachment($path);
It is better to use this.
you can get phpmailer file from https://github.com/PHPMailer/PHPMailer
<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
?>
There is lots here to try to digest but the following line looks wrong.
$header = "From: ".$from_name." <usman_86#rocketmail.com>".$from_mail. $eol;
When resolved, this would appear as:
"From: my_reply_to#flowsleeve.com <usman_86#rocketmail.com>Find Dealer # flowsleeve\r\n"
The reply-to address is also wrong, see the full printout of the header to see what I mean.
Tip: To make it easier I'd suggest using variables that are named the
same as the parameters supplied to the function mail_attachment ~ I
keep having to count which parameter refers to which variable.
The entire header appears like this:
From: my_reply_to#flowsleeve.com <usman_86#rocketmail.com>Find Dealer # flowsleeve
Reply-To: Find Dealer # flowsleeve
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="2642aff44ba290c53e0574e15444e12f"
Content-Transfer-Encoding: 7bit
--2642aff44ba290c53e0574e15444e12f
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 8bit
--2642aff44ba290c53e0574e15444e12f
Content-Type: application/octet-stream; name="pdf.pdf
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="pdf.pdf
--2642aff44ba290c53e0574e15444e12f--
From previous experience of dealing with attachments the formatting is critical - it MUST be exactly right in terms of line endings or it will fail.
Some pointers that might help:
There should be only one new line before a boundary.
There should be 2 dashes only after the last boundary.
There are 2 places where Content-Transfer-Encoding needs to have a new line before.
Also, I forgot to mention that you call the function mail_attachment with 7 parameters yet the function takes 8 parameters. The one that appears to not be supplied in the function call is $from_mail

send email in php with attachment

i have use this code in php mail send with attachment. I am using the Apache http server with wamp.
<?php $to = 'santosh_091020#rediffmail.com';
// Declaring the necessary variables for mail sending :
$subject = 'Testing sendmail.exe';
$name = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$mob = $_REQUEST['mob'] ;
$msg = $_REQUEST['msg'] ;
$message = ' santosh enquire \n\nName: '.$name.' \n Email:'. $email.' \n Mobile:'. $mob.' \n Message: '.$msg.' \n ';
// Declaration of the attributes for attachment.
$upload_name=$_FILES["upload"]["name"];
$upload_type=$_FILES["upload"]["type"];
$upload_size=$_FILES["upload"]["size"];
$upload_temp=$_FILES["upload"]["tmp_name"];
$fp = fopen($upload_temp, "rb");
$file = fread($fp, $upload_size);
fclose($fp);
$file = chunk_split(base64_encode($file));
$num = md5(time());
// Defining the contents of the header.
$headers = "From: ".$email. "\r\n" . "CC: santosh#creativecrows.com" ;
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary=".$num."\r\n";
$headers .= "--$num\r\n";
//$headers .= "Message-ID: <".gettimeofday()." TheSystem#".$_SERVER['SERVER_NAME'].">\r\n";
$headers .= "X-Mailer: PHP v".phpversion()."\r\n";
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 8bit\r\n";
$headers .= "".$message."\n";
$headers .= "--".$num."\n";
$headers .= "Content-Type:".$upload_type." ";
$headers .= "name=\"".$upload_name."\"r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; ";
$headers .= "filename=\"".$upload_name."\"\r\n\n";
$headers .= "".$file."\r\n";
$headers .= "--".$num."--";
//$data = chunk_split(base64_encode($data));
// sending the mail.
if(mail($to, $subject, $message, $headers))
{
echo "Email sent";
send();
}
else
{
echo "Email sending failed";
}
//send mail in client
function send()
{
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$to= trim($email);
$subject = 'thanx';
$message = '<html><head><title>HTML email</title></head>
<body style="background-color:#000099;"><p style="color:#000099;">This email contains HTML Tags!</p><table><tr><th>Firstname</th><th>Lastname</th></tr><tr><td>John</td><td>Doe</td></tr></table></body></html>';$headers1 = 'MIME-Version: 1.0' . "\r\n";
$headers1.= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers1.= "From: ".$email;
if(mail($to, $subject, $message,$headers1))
{
echo "Email sent";
}
else
{
echo "Email sending failed";
echo $to;
echo $subject;
echo $message;
}
}
?>
but i got the following error;
Delivery to the following recipient failed permanently:
1.0#localhost
Technical details of permanent failure:
DNS Error: Domain name not found.
please help me. Thnx in advance.
Check this URL,
seems your header info is not absolute
http://webcheatsheet.com/php/send_email_text_html_attachment.php
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup server
$mail->Port = '';
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = '';
$mail->FromName = '';
$mail->AddAddress($row['client_email'], ''); // Add a recipient
$mail->AddReplyTo('', 'Information');
$mail->AddCC('cc#example.com');
$mail->AddBCC('bcc#example.com');
$mail->WordWrap = 50;
// Set word wrap to 50 characters
$mail->AddAttachment('kurtacompany/techreporting/upload/"'.$row['file1'].'"'); // Add attachments
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = '';
$mail->Body = '<p>type whatever you want</p>';
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';

Adding attachments to mail

i've this script that works perfectly but the attachments are null (i mean i can see the attachments..but every file I load is 0 kb as size)
here is the code :
allegato means attachment
$path = $allegato['tmp_name'];
$fp = fopen($path, 'r');
do //we loop until there is no data left
{
$data = fread($fp, 8192);
if (strlen($data) == 0) break;
$content .= $data;
} while (true);
$content_encode = chunk_split(base64_encode($content));
$mime_boundary = "<<<--==+X[".md5(time())."]";
$headers .= "From:".$email."\r\n";
$headers .= "To: me <mail#gmail.com>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed;\r\n";
$headers .= " boundary=\"".$mime_boundary."\"";
$message .= "This is a multi-part message in MIME format.\r\n";
$message .= "\r\n";
$message .= "--".$mime_boundary."\r\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message .= "\r\n";
$message .= "Email sent from:".$nome." \r\n";
$message .= $messaggio."\r\n";
$message .= "--".$mime_boundary."\r\n";
$message .= "Content-Type: ".$allegato_type."\"\r\n";
$message .= " name=\ ".$allegato_name."\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment;\r\n";
$message .= " filename=\ ".$allegato_name."\"\r\n";
$message .= "\r\n";
$message .= $content_encode;
$message .= "\r\n";
$message .= "--".$mime_boundary."\r\n";
$ok = mail("mail#gmail.com", $object, $message, $headers);
if($ok)
{
echo'<script type="text/javascript">alert("mail sent successfully ! ");</script>';
}
else
{ echo'<script type="text/javascript">alert("mail failed! ");</script>';}
can someone help with attachments please ?(every file sent is 0 kb, how i fix it ?)
I suggest to use PHPMailer!
It is freely available from http://sourceforge.net/projects/phpmailer/
Just put it in a directory on the server, include its main php and your life will become a joy when sending e-mails from php.
I have a function for an easy start that I can provide to you for quick results:
require("/path/to/class.phpmailer.php");
function mail_sender($from_name,$from_email,$to_email,$subject,$mailtext,$att = false) {
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "localhost"; // specify main and backup server
$mail->SMTPAuth = false; // turn on SMTP authentication
$mail->From = $from_email;
$mail->FromName = $from_name;
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->CharSet="utf-8";
$mail->Subject = $subject;
$mail->Body = $mailtext;
$mail->AltBody = "";
$mail->AddAddress($to_email);
if ($att) {
$mail->AddAttachment("include/attachment.doc");
}
if(!$mail->Send()) {
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
}

Categories