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;
}
}
Related
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';
}
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';
I have a function that is supposed to be attaching a file to an outgoing email. For some reason it is only sending blank files.
Can someone help? I have verified that the files themselves are being uploaded correctly, and are at the exact location needed for this function to work. Only .pdf, .doc, and .docx are allowed
Also, this is on a Windows Server... (I know, I know...YUCK!)
Here is the function:
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = str_replace('/','\\',$path.$filename);
$file_size = filesize($file);
$handle = fopen($file, "rb");
$contenta = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($contenta));
$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";
$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"; // use different content types here
$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."--";
if (mail($mailto, $subject, "", $header)) {
return true; // or use booleans here
} else {
return false;
}
}
And here is the code using this:
//resume
$errors="";
$dbDir="/candidate-resources/files/temp/";
$baseDir=$_SERVER['DOCUMENT_ROOT'].$dbDir;
$validTypes=array(".doc",".pdf",".docx");
$filesToAdd=array();
$atLeastOne=false;
$valid=false;
$qs="";
if(count($_FILES)>0){
foreach($_FILES as $k=>$v){
if($v['size']>0){
$ext=substr($v['name'],strrpos($v['name'],"."));
if(!in_array($ext,$validTypes)){
$errors='Only ".doc", ".docx", and ".pdf" files can be uploaded. "'.$ext.'" is not a valid file type.';
}
}
}
}
$requireds=array("name","email","message");
foreach($_POST as $k=>$v){//check for injection and spammers
if(preg_match("/(%0A|%0D|\\n+|\\r+)(content-type:|to:|cc:|bcc:)/i",$v) || strpos($v,"http://")!==false || strpos($v,"www.")!==false){
$errors="HTML, website addresses, and scripting code are not allowed in any field. Please check your entries and try again.";
}
$post[$k]=strip_tags(trim(htmlentities($v)));
}
unset($_POST);
foreach($requireds as $r){
if(!strlen(trim($post[$r]))){
$errors.="<li>".ucwords($r)."</li>";
}
}
if(strlen(trim($errors))){
$errors="These fields were left blank. Please fix and resubmit.<ul>".$errors."</ul>";
}
else{
if(ereg("([[:alnum:]\.\-]+)(\#[[:alnum:]\.\-]+\.+)",$post['email'])!=true){
$errors="<p>You must enter a valid email address.</p>";
}
else{
$filename = '';
$ext = '';
// upload the file, then attach it to the email, then delete it
foreach($_FILES as $k=>$v){
if($v['size']!=0){
$atLeastOne=true;
$ext=substr($v['name'],strrpos($v['name'],"."));
move_uploaded_file($v['tmp_name'], $baseDir . "/" . $v['name']);
$filename = $v['name'];
}
}
$to = 'avalid#emailaddress';
$subject="Contact Form";
$headers="From: ".$post["name"]." <".$post["email"].">\r\nReply-To: ".$post["email"]."\r\n";
$message=$subject."\r\n=================================================\r\n\r\n";
foreach($post as $k=>$v) {
if(strlen(trim($v))){
$message.=ucwords(str_replace("_"," ",$k)).": {$v}\r\n";
}
}
if(strlen($filename) > 0) {
mail_attachment($filename, $baseDir, $to, $post["email"], $post["name"], $post["email"], $subject, $message);
//now delete the temp file
if (file_exists(str_replace('/','\\',$baseDir.$filename))) {
unlink(str_replace('/','\\',$baseDir.$filename)); // delete it here only if it exists
}
}else{
mail($to,$subject,$message,$headers);
}
$errors="true";
}
}
please forgive... I just inherited this code (that is: #1 7 years old, #2 now they wanted the ability to attach a file to this email)
Start using Swiftmailer (documentation) or PhpMailer, your life will be easier...
Swiftmailer example:
require_once 'lib/swift_required.php';
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john#doe.com' => 'John Doe'))
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
->setBody('Here is the message itself')
->attach(Swift_Attachment::fromPath('my-document.pdf'));
$mailer->send($message);
PhpMailer example :
$mail = new PHPMailer(); // defaults to using php "mail()"
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->AddAddress("whoto#otherdomain.com", "John Doe");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAttachment("images/phpmailer.gif"); // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
I prefer Swiftmailer, but you select you best choice ;-)
I changed my function around some, and this works:
function mail_attachment($from, $fromname, $to, $subj, $text, $filename){
$f = fopen($filename,"rb");
$un = strtoupper(uniqid(time()));
$head = "From: $fromname <$from>\n";
$head .= "To: $to\n";
$head .= "Subject: $subj\n";
$head .= "X-Mailer: PHPMail Tool\n";
$head .= "Reply-To: $from\n";
$head .= "Mime-Version: 1.0\n";
$head .= "Content-Type:multipart/mixed;";
$head .= "boundary=\"----------".$un."\"\n\n";
$zag = "------------".$un."\nContent-Type:text/html;\n";
$zag .= "Content-Transfer-Encoding: 8bit\n\n$text\n\n";
$zag .= "------------".$un."\n";
$zag .= "Content-Type: application/octet-stream;";
$zag .= "name=\"".basename($filename)."\"\n";
$zag .= "Content-Transfer-Encoding:base64\n";
$zag .= "Content-Disposition:attachment;";
$zag .= "filename=\"".basename($filename)."\"\n\n";
$zag .= chunk_split(base64_encode(fread($f, filesize($filename))))."\n";
return #mail("$to", "$subj", $zag, $head);
}
(without the need for a 3rd party include)
I am using a class i found to email something with attachment, yet when i send the message it dosen't appear. i'm trying to send an HTML message but even a regular one dosen't send.
Can't spot the error.
The email sends fine only the message is empty
Can someone take a look please?
Code:
<?php
class mailer{
var $email_to;
var $email_subject;
var $headers;
var $mime_boundary;
var $email_message;
//sets up variables and mail email
function mailer($email_to,$email_subject,$email_message,$headers){
$this->email_to=$email_to;
$this->email_subject=$email_subject;
$this->headers = $headers;
$semi_rand = md5(time());
$this->mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$this->headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$this->mime_boundary}\"";
$this->email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$this->mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n".
$email_message . "\n\n";
}
//adds attachment
function attach($fileatt_type,$fileatt_name,$fileatt_content){
$data = chunk_split(base64_encode($fileatt_content));
$this->email_message .= "--{$this->mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$this->mime_boundary}\n";
unset($data);
unset($file);
unset($fileatt);
unset($fileatt_type);
unset($fileatt_name);
}
//send email
function send(){
return mail($this->email_to, $this->email_subject, $this->email_message, $this->headers);
}
//extra functions to make life easier
//send email with imap
function imap_send(){
return imap_mail($this->email_to, $this->email_subject, $this->email_message, $this->headers);
}
//read file and add as attachment
function file($file){
$o=fopen($file,"rb");
$content=fread($o,filesize($file));
fclose($o);
$name=basename($file);
$type="application/octet-stream";
$this->attach($type,$name,$content);
}
//read directory and add files as attachments
function dir($dir){
$o=opendir($dir);
while(($file=readdir($o)) !==false){
if($file != "." && $file != ".."){
if(is_dir($dir."/".$file)){
$this->dir($dir."/".$file);
}else{
$this->file($dir."/".$file);
}
}
}
}
}
message populate:
$message = "<span style='color:red;'>NOTICE: test tesx..";
$message .= "test text";
$message .= "Please text test.</span>";
$message .= "If you encounter any problems please contact at contact#shibby.co.il";
calling the class:
$mailer=new mailer($mail_to,$subject,$message,"From: $from_mail");
$mailer->file($fileName);
$test=$mailer->send();
For sending mail with attachment.
<?php
//If there is no error, send the email
if(isset($_POST['ur_submit_button_name'])) {
$uname=$_POST['uname'];
$to = $_POST['mailid'];
$mobileno=$_POST['mobile'];
$location=$_POST['location'];
$from = "Yourname <Yourname#domainname.com>";
$subject = "This is the subject";
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// attachment name
$filename = "ip.zip";//store that zip file in ur root directory
$attachment = chunk_split(base64_encode(file_get_contents('ip.zip')));
// main header
$headers = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
// no more headers after this, we start the body! //
$body = "--".$separator.$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "This is a MIME encoded message.".$eol;
// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;
// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";
// send message
if (mail($to, $subject, $body, $headers)) {
$mail_sent=true;
echo "mail sent";
} else {
$mail_sent=false;
echo "Error,Mail not sent";
}
}
?>
How can i send a mail in php with two attachment.
And the attachments are csv files
Can any one give a simple sample code
http://www.emanueleferonato.com/2008/07/22/sending-email-with-multiple-attachments-with-php/
<?php
// 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>";
}
?>
I would sugest you to use a library like PHPMailer or Zend_Mail. It's much easer and secure.
Example:
PHPMailer
$mail = new PHPMailer();
$mail->From = $from;
$mail->FromName = $fromName;
$mail->AddAddress($to, $toName);
$mail->AddReplyTo($from, $fromName);
$mail->CharSet = 'UTF-8';
$mail->AddAttachment($pathtofile);
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $bodyHTML;
$mail->Send();
Zend_Mail
(See the documentation http://framework.zend.com/manual/en/zend.mail.html)