Send URL attachment with PHP mail() function - php

I am sending attachments by uploading through <input type="file" /> but now I want to know if we can send attachments just using URL of a file?
Like if I add <input type="url" name="file[]" /> and I need to send this as attachment not in body as inline link in message.
For now I am using this code:
HTML:
<form method="post" action="code.php" enctype="multipart/form-data">
<input type="file" name="file[]" multiple="multiiple" />
<button type="submit">Submit</button>
</form>
PHP:
<?php
foreach(array_combine($_FILES['file']['tmp_name'], $_FILES['file']['name']) as $tmp_name => $file_name ) {
$filetmp[] = $tmp_name;
$filename[] = $file_name;
}
// email fields: to, from, subject, and so on
$to = "receiver_email";
$from = "sender_email";
$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($filetmp);$x++){
$file = fopen($filetmp[$x],"rb");
$data = fread($file,filesize($filetmp[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$filename[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$filename[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
mail($to, $subject, $message, $headers);
?>
Thanks

Related

Sending attachment (.docx) with PHP mail();

while sending a mail using PHP mail() without attachment working fine.
But while sending with attachment sending Failed
please help me.
Whats wrong in my code?
Thanks in advance.
My HTML code is shown below
index.html
<html>
<head>
<title>Mail</title>
</head>
<body>
<form method="POST" action="mail.php" enctype="multipart/form-data">
<input type="text" name="fromName">
<input type="email" name="fromEmail">
<input type="file" name="fileAttach">
<input type="submit" name="submit">
</form>
</body>
</html>
The following is my Mail code
mail.php
<?php
if (isset($_POST['submit'])) {
/* $mailto = $_POST["mailTo"];*/
$mailto = "to#gmail.com";
$from_mail = $_POST["fromEmail"];
$replyto = $_POST["fromEmail"];
$from_name = $_POST["fromName"];
/*$message = $_POST["message"];*/
$message="This is message part";
/*$subject = $_POST["subject"];*/
$subject ="this is subject part";
$filename = $_FILES["fileAttach"]["name"];
$content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$uid = md5(uniqid(time()));
$name = basename($file);
$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";
// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
$header .= "Content-type:text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
// User Message you can add HTML if You Selected HTML content
$header .= "<div style='color: red'>" . $message . "</div>\r\n\r\n";
$header .= "--" . $uid . "\r\n";
$header .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n"; // For Attachment
$header .= $content . "\r\n\r\n";
$header .= "--" . $uid . "--";
if (mail($mailto, $subject, $message, $header)) {
echo "<script>alert('Success');</script>"; // or use booleans here
} else {
//echo mysqli_error();
echo "<script>alert('Failed');</script>";
}
}
Is there anything to add or change in the code?

Email attachment using php, file can't open in email

This is my code, in this case, the code works perfectly and I got the attachment in the mail but the attached file can't be opened. Then I downloaded the file and tried to open it, it shows an error "either not a supported file type or file has been damaged(For example, it was send as an email attachment and wasn't correctly decoded)"
<form action="#" method="POST" enctype="multipart/form-data" >
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="submit" name="upload" value="Upload" />
<br/>
</form>
<?php
if($_POST) {
for($i=0; $i < count($_FILES['csv_file']['name']); $i++){
$ftype[] = $_FILES['csv_file']['type'][$i];
$fname[] = $_FILES['csv_file']['name'][$i];
}
// array with filenames to be sent as attachment
$files = $fname;
// email fields: to, from, subject, and so on
$to = "example#gmail.com";
$from = "example#gmail.com";
$subject ="My subject";
$message = "My message1";
$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>";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>E-mail with Attachment</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD']=="POST"){
// we'll begin by assigning the To address and message subject
$to="example#gmail.com";
$subject="E-mail with attachment";
// get the sender's name and email address
// we'll just plug them a variable to be used later
$from = stripslashes($_POST['fromname'])."<".stripslashes($_POST['fromemail']).">";
// generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// 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}\"";
$message="This is an example";
$message .= "Name:".$_POST["fromname"]."Message Posted:".$_POST["modlist"];
$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";
// now we'll process our uploaded files
foreach($_FILES as $userfile){
// store the file information to variables for easier access
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
// if the upload succeded, the file will exist
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)){
// open the file for a binary read
$file = fopen($tmp_name,'rb');
// read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// now we encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// 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.
// NOTE: we don't set another boundary to indicate that the end of the
// file has been reached here. we only want one boundary between each file
// we'll add the final one after the loop finishes.
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
// here's our closing mime boundary that indicates the last of the message
$message.="--{$mime_boundary}--\n";
// now we just send the message
if (#mail($to, $subject, $message, $headers))
echo "Message Sent";
else
echo "Failed to send";
} else {
?>
<p>Send an e-mail with an attachment:</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="form1">
<p>Your name: <input type="text" name="fromname"></p>
<p>Your e-mail: <input type="text" name="fromemail"></p>
<p>Mod List: <textarea name="question" maxlength="1000" cols="25" rows="6" name="modlist"></textarea>
<p>File: <input type="file" name="file1"></p>
<p>File: <input type="file" name="file2"></p>
<p>File: <input type="file" name="file3"></p>
<p>File: <input type="file" name="file4"></p>
<p>File: <input type="file" name="file5"></p>
<p>File: <input type="file" name="file6"></p>
<p>File: <input type="file" name="file7"></p>
<p><input type="submit" name="Submit" value="Submit"></p>
</form>
<?php } ?>
</body>
</html>

Submit form with attachment to email

My code here is:
<form action="#" method="POST" enctype="multipart/form-data" >
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="submit" name="upload" value="Upload" />
<br/>
</form>
<?php
if($_POST) {
for($i=0; $i < count($_FILES['csv_file']['name']); $i++){
$ftype[] = $_FILES['csv_file']['type'][$i];
$fname[] = $_FILES['csv_file']['name'][$i];
}
// array with filenames to be sent as attachment
$files = $fname;
// email fields: to, from, subject, and so on
$to = "example#gmail.com";
$from = "example#gmail.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>";
}
}
?>
I got the code from here: https://stackoverflow.com/a/27565430/4357238
the form successfully sends the email and when i get the email, the name of the file(s) show up but the file is an empty file (0 bytes).
For example, i send a file called car.jpg and when it gets to my email, it shows up on my email as car.jpg but when i download the file and open the file, it says the file is broken and it cannot be opened because the file is empty.
what is wrong and how can i fix it?

php mail() function to send mail with an attachment

I have created two scripts for this HTML and a corresponding PHP.
HTML markup:
<html>
<body>
<form action="http://senindiaonline.in/admar/non-series-numbers-db.php" method="post" target="_blank" name="non_series_numbers_db" enctype="multipart/form-data">
<label for="emp-id">Employee ID: </label>
<input type="text" name="emp-id" id="emp-id" maxlength="15" style='text-transform:uppercase'/>
<br/>
<label for="no-csv">If you have a mobile number database in CSV file format upload that here: </label>
<input name="no-csv" id="no-csv" type="file" accept=".csv"/>
<br/>
<label for="no-xls">If you have a mobile number database in XLS (excel) file format upload that here: </label>
<input name="no-xls" id="no-xls" type="file" accept=".xls"/>
<br/>
<label for="no-xlsx">If you have a mobile number database in XLSX (excel) file format upload that here: </label>
<input name="no-xlsx" id="no-xlsx" type="file" accept=".xlsx"/>
<br/>
<input name="send" value="Send" type="submit" id="send"/>
</form>
</body>
</html>
PHP script:
<?php
error_reporting(0);
$email_to = 'senindiagroup#gmail.com';
$email_subject = "Non-Seriesed Mobile Number Database from Ad&Marketing Employee Panel of Sen India Online inc.";
$emp_id = $_POST['emp-id'];
$sub="Employee ID: $emp_id";
$bound_text = "jimmyPI23";
$bound = "--" .$bound_text. "\r\n";
$bound_last = "--" .$bound_text. "--\r\n";
$email_message .= "If you can see this MIME than your client doesn't accept MIME types! \r\n" .$bound;
$email_message .= "Content-Type: text/html; Charset=\"iso-8859-1\"\r\n" ."Content-Transfer-Encoding: 7bit\r\n\r\n" ."$sub\r\n" .$bound;
//getting temporary file location with name
$a=file_get_contents($_FILES['no-csv']['tmp_name']);
$b=file_get_contents($_FILES['no-xls']['tmp_name']);
$c=file_get_contents($_FILES['no-xlsx']['tmp_name']);
//getting original name of the file you uploaded
$name=$_FILES["no-csv"]["name"];
$name1=$_FILES["no-xls"]["name"];
$name2=$_FILES["no-xlsx"]["name"];
$email_message .= "Content-Type: {\"application/octet-stream\"}; \n" . "name=\"$name\ "\n" . "Content-Transfer-Encoding: base64\r\n" ."Content-Disposition: attachment; \n" . " filename=\"$name\ "\n"."\r\n" .chunk_split(base64_encode($a)).$bound;
mail($email_to, $email_subject, $email_message, $headers);
?>
The error is:
syntax error showing on line 31, attach file with mail command.
And the mail is not send. I solve this error with DreamWeaver suggestion. Then the mail is send, but the attachment is not included in the mail.
This is the example of sending multiple attachments in mail
<?php
for($i=0; $i < count($_FILES['csv_file']['name']); $i++){
$ftype[] = $_FILES['csv_file']['type'][$i];
$fname[] = $_FILES['csv_file']['name'][$i];
}
// array with filenames to be sent as attachment
$files = $fname;
// email fields: to, from, subject, and so on
$to = "example#gmail.com";
$from = "example#gmail.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 simple solution use phpmailer library, that would be easy to use,easy to configure.

Send 2 files by email using a form HTML and PHP

Hi everybody I'm searching to solve a problem (looks easy but I don't find a solution).
I have a form HTML and I'm trying to send datas and files to a specific email.
The email arrives correctly but the 2 file attached have a strange name, it look like a temporary name file. It like I lost the name of the file and the extension.
Somebody could help me to understand what I'm doing wrong?
I'm not really an expert on PHP.
Thanks!
HTML file
<form id="form1" name="form1" method="post" action="email2.php" enctype="multipart/form-data">
<fieldset>
<legend>Canditatura</legend>
<label>Nome:</label> <input type="text" placeholder="Inserisci il tuo nome" name="nome" size="30px" required="true"><br>
<label>Cognome:</label> <input type="text" placeholder="Inserisci il tuo cognome" name="cognome" size="30px" required="true"><br>
<label>Email:</label> <input type="email" name="email" placeholder="example#example.it" size="30px" required="true"><br>
<label>Telefono:</label> <input type="tel" name="telefono" placeholder="+39" size="30px"><br>
<label>Allegato 1:</label> <input type="file" id="allegato" name="allegato" required="true"><br>
<label>Allegato 2:</label> <input type="file" id="allegato2" name="allegato2" required="true"><br><br><br>
<label class="lprivacy"><input type="checkbox" required="true">Accetto normativa sulla Privacy</label><input type="submit" value="Invia Canditatura" name="submit">
</fieldset>
</form>
PHP File
<?php
$allegato = $_FILES['allegato']['tmp_name'];
$allegato_type = $_FILES['allegato']['type'];
$allegato_name = $_FILES['allegato']['name'];
$allegato2 = $_FILES['allegato2']['tmp_name'];
$allegato2_type = $_FILES['allegato2']['type'];
$allegato2_name = $_FILES['allegato2']['name'];
$email = $_POST['email'];
$nome = $_POST['nome'];
$cognome = $_POST['cognome'];
$telefono = $_POST['telefono'];
mail_attachment("test#test.com","Subject","Nuova canditatuda da <b>$nome $cognome</b>. <br> Telefono: $telefono <br> Email: $email ",array("$allegato","$allegato2"));
function mail_attachment($to, $subject, $message, $files) {
$headers = "From: no-reply#mail.com";
$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/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
foreach ($files as $file) {
$filename = end(explode("/",$file));
$data = file_get_contents($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$file\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$file\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
echo (#mail($to, $subject, $message, $headers)) ? "<p>Messaggio spedito correttamente a $to!</p>" : "<p>ERRORE! Messaggio non spedito a $to!</p>";
} // mail-attachment ?>
According to your code, your sending temp file but your not sending the original file name, so that's the received file name has some random file name.
Check bellow code
<?php
$email = $_POST['email'];
$nome = $_POST['nome'];
$cognome = $_POST['cognome'];
$telefono = $_POST['telefono'];
mail_attachment("test#test.com","Subject","Nuova canditatuda da <b>$nome $cognome</b>. <br> Telefono: $telefono <br> Email: $email ",array("allegato","allegato2"));
function mail_attachment($to, $subject, $message, $files) {
$headers = "From: no-reply#mail.com";
$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/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
foreach ($files as $f) {
$file = $_FILES[$f]['tmp_name'];
$filename = $_FILES[$f]['name'];;
$data = file_get_contents($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$file\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$file\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
echo (#mail($to, $subject, $message, $headers)) ? "<p>Messaggio spedito correttamente a $to!</p>" : "<p>ERRORE! Messaggio non spedito a $to!</p>";
} // mail-attachment ?>
Instead of passing file uploaded paths, I passing HTML elements to the function, so that it will fetch necessary Information and attach file(s) and it will send mail.

Categories