Sending an image to email via PHP - php

can you please help me with this code. i am trying to embed a image in my mail and its showing as string of alphanumeric ..
function send_mail_pear()
{
$crlf = "\n";
$to = "mail#mail.in";
$head = ("From: mail#mail.in". "\r\n");
$head .= "Content-type: text/html\r\n";
$head .= "Content-Type: image/jpeg";
$mime = new Mail_mime($crlf);
echo $head. "<br/>";
$mime->setHTMLBody('<html><body><img src="map_6.gif"> <p>You see this image.</p></body></html>');
$mime->addHTMLImage('map_6.gif', 'image/gif');
$subject = "Test mail";
$mailBody = $mime->get();
$mail =& Mail::factory('mail');
echo $mailBody ;
/*if(mail($to, $subject, $mailBody, $head)){
echo "successful";
} else {
echo "Mail Not sent";
}
}

I believe you have to link to the image as "cid:yourcontentid", and specify "yourcontentid" as a parameter to addHTMLImage.
You can consult the documentation for more information.

you can just attach it using. or i suggest the least painful option will be to host the image on some server and send an HTML email.
the body will look like
<html>
<p>
<img src='http://yourserver.com/YOURIMAGE.gif' />
</p>
</html>
EDIT:
to attach images or files to an email try something like this
$to = "someome#anadress.com";
$from = "SOME NAME ";
$subject = "SUBJECT";
$fileatt = "./FILENAME.gif";
$fileatttype = "image/gif";
$fileattname = "ATTACHMENTNAME.gif";
$headers = "From: $from";
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);
$data = chunk_split(base64_encode($data));
$rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$rand}x";
$headers .= <<<HEADER
MIME-Version: 1.0\n
Content-Type: multipart/mixed;\n
boundary="{$mime_boundary}"
HEADER;
$message = <<<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
\n\n
–{$mime_boundary}\n
Content-Type: {$fileatttype};\n
name="{$fileattname}"\n
Content-Disposition: attachment;\n
filename="{$fileattname}"\n
Content-Transfer-Encoding: base64\n\n
{$data}\n\n
-{$mime_boundary}-\n
MESSAGE;
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}

The answer by Matthias Vance is part of the story.
If you want to send a self-contained HTML mail, then it needs to be sent as an mhtml type (NB the content type for this varies on different implementations - it should be multipart/related but frequently is message/rfc822). There is however a formal definition of the structure in RFC 2557. Each of the components should be a seperate attachment. This also means that each URL has to be rewritten to use a local reference and the cid scheme - IIRC, the PEAR class does not do this for you.
There is some documentation on the net e.g. this one - but do not fall into the trap of believing this is suitable for anything other than sending emails / saving web pages locally - MSIE does not handle mhtml files delivered over HTTP correctly.
I'm not aware of any off the shelf package for generating mhtml files / emails - but there are some for parsing such files. Writing a tool to do this would be straightforward but not trivial.

Related

Empty message when sending zip file with PHP

**Update: Updated the code and added the email contents as seen in Gmail. **
I have a problem which I've been trying to solve a couple of days. But since I have been unable to make any progress, I'd like the help of someone else. I'm trying to send a zip file from my server to my email. However, the email is being sent empty. This is the code:
`$headers = "From: $from";
/* Generate boundary string */
$random = md5(time());
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random."\"";
/* Read the file */
$attachment = chunk_split(base64_encode(file_get_contents("backup-$date-$time-9.zip")));
/* Define body */
$message = "--PHP-mixed-$random
Content-Type: text/plain; charset=\"iso-8859-1\"
Attached, please find your backup file.
--PHP-mixed-$random
Content-Type: application/zip; name=backup-$date-$time-9.zip
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random--"; // no intendation
$mail = mail($email, $subject, $message, $headers);
echo $mail ? "Email sent<br>" : "Email sending failed<br>";`
Thanks to all reading and wanting to help.
The resulting email as seen in Gmail is
Attached, please find your backup file.
--PHP-mixed-e44b531b0e0538185289abc521eda78d
Content-Type: application/zip; name=backup-29-11-2014-1417275285-9.zip
Content-Transfer-Encoding: base64
Content-Disposition: attachment
UEsDBBQAAAAIAFZ8fUUs...sUEsFBgAAAAACAAIAeAAAAD4B
AAAAAA==
--PHP-mixed-e44b531b0e0538185289abc521eda78d--
I got it working by doing the following changes:
Removed space character in From: headers, it's an invalid header otherwise
Changed boundary: to boundary=
Removed intendation in $message because that seems to break the email. The boundary string --PHP-mixed-random separates the different parts of the email, like plain text, html text, attachments from each other. When there are spaces in front of the boundary separator, it is not interpreted as the separator anymore, but as normal text.
Here's the code:
<?php
$from = "xxx#myserver";
$email = "xxx#gmail.com";
$subject = "backup file";
$date = "29-11-2014";
$time = "1417275285"; // test file "backup-29-11-2014-1417275285-9.zip" in the same folder
$headers = "From: $from"; // remove space
/* Generate boundary string */
$random = md5(time());
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random."\""; // : to =
/* Read the file */
$attachment = chunk_split(base64_encode(file_get_contents("backup-$date-$time-9.zip")));
/* Define body */
$message = "--PHP-mixed-$random
Content-Type: text/plain; charset=\"iso-8859-1\"
Attached, please find your backup file.
--PHP-mixed-$random
Content-Type: application/zip; name=backup-$date-$time-9.zip
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--PHP-mixed-$random--"; // no intendation
$mail = mail($email, $subject, $message, $headers);
echo $mail ? "Email sent<br>" : "Email sending failed<br>";

Send attachment file using mail () in PHP

I had reference this solution from other post and I tried modify the content to suit my requirement.
Here is the code that I implemented to send attachment file via mail using PHP.
$htmlbody = " Your Mail Contant Here.... You can use html tags here...";
$to = "foo#bar.com"; //Recipient Email Address
$subject = "Test email with attachment"; //Email Subject
$headers = "From: foo#bar.com\r\nReply-To: foo#bar.com";
$random_hash = md5(date('r', time()));
$headers .= "\r\nContent-Type: multipart/mixed;
boundary=\"PHP-mixed-".$random_hash."\"";
// Set your file path here
$path = $_FILES["cv"]["name"];
$attachment = chunk_split(base64_encode(file_get_contents($path)));
//define the body of the message.
$message = "--PHP-mixed-$random_hash\r\n"."Content-Type: multipart/alternative;
boundary=\"PHP-alt-$random_hash\"\r\n\r\n";
$message .= "--PHP-alt-$random_hash\r\n"."Content-Type: text/plain;
charset=\"iso-8859-1\"\r\n"."Content-Transfer-Encoding: 7bit\r\n\r\n";
//Insert the html message.
$message .= $htmlbody;
$message .="\r\n\r\n--PHP-alt-$random_hash--\r\n\r\n";
//include attachment
$message .= "--PHP-mixed-$random_hash\r\n"."Content-Type: application/zip;
name=\"$path\"\r\n"."Content-Transfer-Encoding:
base64\r\n"."Content-Disposition: attachment\r\n\r\n";
$message .= $attachment;
$message .= "/r/n--PHP-mixed-$random_hash--";
//send the email
$mail = mail( $to, $subject , $message, $headers );
echo $mail ? "Mail sent" : "Mail failed";
I able to get the attachment file but I cant open it.
It show me the error of "The application you chose ("") could not be found. Check the file name or choose another application."
Can anyone correct my error..?
It seems that the problem relies in the file name after download. The server did the job and sent the email and this is rather a client side problem.
Check the filename extension and make sure it is the same as the side that sent it, If not make sure u correct your PHP code naming function.
Make sure the application that reads that filetype is available on your PC.
Try to open the file on a different computer.

PDF file won't attached return 0 bytes corrupted file

When trying to attached the pdf file, it cannot be open in PDF and says its corrupted. I tried several solution found in the web but it didn't work. The file is being attached and sent but when you open the PDF its corrupted although it is being downloaded but with invalid size(1kb) wherein the original size is around 0.40mb
Any help would highly be appreciated.
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message)
{
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = "\n";
//$pdfdoc is PDF generated by FPDF
$attachment = chunk_split(base64_encode($pdfdoc));
// main header
$headers = "From: ".$from_name.$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($mailto, $subject, $body, $headers)) {
echo "mail send ... OK";
} else {
echo "mail send ... ERROR";
}
}
/*
// Only accept POSTs from authenticated source
if ($_POST['HandshakeKey'] != 'outsource-phil') {
echo "<h1>You are not who you say you are, mister man.</h1>";
die();
}
*/
// EDIT FROM HERE DOWN TO
// CUSTOMIZE EMAIL
//*
// File to attach
$filename = "outsource.pdf";
$path = $_SERVER['DOCUMENT_ROOT']. "/wp-content/uploads/2014/02/";
// Who email is FROM
$from_name = "COmpany Name";
$from_mail = "company#domain.com";
$replyto = "company#domain.com";
// Whe email is going TO
$mailto = $_POST['Field3'];
// Subject line of email
$subject = "Your file has arrived!";
// Content of email message (Text only)
$requester = $_POST['Field12']; // Comes from Wufoo WebHook
$message = "Hey $requester,
Your custom email message
goes here";
// Call function to send email
mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message);
Edit #1: After doing some research myself, I found that it's much easier to use an external library that sets up the e-mail with the attachment for you. I've done this using PHPMailer, which can be downloaded from https://github.com/Synchro/PHPMailer.
The following code should do what you're looking for. I highly recommend using a library such as PHPMailer.
// File to attach
$filename = "outsource.pdf";
$path = $_SERVER['DOCUMENT_ROOT']. "/wp-content/uploads/2014/02/";
// Who email is FROM
$from_name = "COmpany Name";
$from_mail = "company#domain.com";
$replyto = "company#domain.com";
// Whe email is going TO
$mailto = $_POST['Field3'];
// Subject line of email
$subject = "Your file has arrived!";
// Content of email message (Text only)
$requester = $_POST['Field12']; // Comes from Wufoo WebHook
$message = "Hey $requester,
Your custom email message
goes here";
/*
* The following code requires PHPMailer
*/
require_once('PHPMailer-master/class.phpmailer.php');
$mail = new PHPMailer();
$mail->AddReplyTo($replyto, $from_name);
$mail->SetFrom($from_mail, $from_name);
$mail->AddAddress($mailto, $requester);
$mail->Subject = $subject;
$mail->MsgHTML($message);
$mail->AddAttachment($path . $filename);
if (!$mail->Send()) {
echo "Mail error!";
} else {
echo "Mail success!";
}
You seem to overwrite your PDF file by using the following code:
$str = "Business Plan: \nSome more text";
$fp = fopen("outsource.pdf", 'w+');
fwrite($fp, $str);
fclose($fp);
The w+ option in fopen() will create a new, blank file. You appear to want to send the original file, in which case you wouldn't want these lines of code. What are you trying to accomplish here?

Pass File via mail() PHP

I have a Problem, I would like to send a File (Photoshop, .gif etc.) File via Email with PHP.
I POST the Data from the HTML Document to the following PHP File.
The Problem: I receive the Email but the File is corrupt.
Any Idea why this doesn´t work??
$to = 'admin#example.com';
$subject = 'Order';
$name = strip_tags($_POST['name']);
$email = strip_tags($_POST['email']);
$plz = strip_tags($_POST['plz']);
$city = strip_tags($_POST['city']);
$street = strip_tags($_POST['street']);
$nr = strip_tags($_POST['nr']);
$plzdelivery = strip_tags($_POST['plz-delivery']);
$citydelivery = strip_tags($_POST['city-delivery']);
$streetdelivery = strip_tags($_POST['street-delivery']);
$nrdelivery = strip_tags($_POST['nr-delivery']);
$buttonsize = strip_tags($_POST['button-size']);
$count = strip_tags($_POST['count']);
$message = "Name: ".$name." Email: ".$email." Plz: ".$plz." Stadt: ".$city." Strasse: ".$street." Hnr: ".$nr." Button: ".$buttonsize." Anzahl: ".$count;
$type = $_FILES['file']['type'];
$attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
$filename = $_FILES['file']['name'];
$boundary =md5(date('r', time()));
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
$message="This is a multi-part message in MIME format.
--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"
--_2_$boundary
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit
$message
--_2_$boundary--
--_1_$boundary
Content-Type: application/octet-stream; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--_1_$boundary--";
mail($to, $subject, $message, $headers);
Short answer: Don't even try.
PHP's mail() function is very very short on features. If you're even considering trying to send attachments using it, you are in for a lot of frustration and wasted time.
The best answer I can give you is to use a third party library. There are several good ones available. Why waste weeks of your time writing something that isn't going to be good enough when others have already spent years doing it for you and getting it right.
My suggestion would be phpMailer, but several others exist as well.
You should install the pear Mail_Mime package, it will allow you to easily attach a file.
http://pear.php.net/manual/en/package.mail.mail-mime.addattachment.php

How to use TCPDF with PHP mail function

$to = 'my#email.ca';
$subject = 'Receipt';
$repEmail = 'rep#sales.ca';
$fileName = 'receipt.pdf';
$fileatt = $pdf->Output($fileName, 'E');
$attachment = chunk_split($fileatt);
$eol = PHP_EOL;
$separator = md5(time());
$headers = 'From: Sender <'.$repEmail.'>'.$eol;
$headers .= 'MIME-Version: 1.0' .$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
$message = "--".$separator.$eol;
$message .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$message .= "This is a MIME encoded message.".$eol;
$message .= "--".$separator.$eol;
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$message .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$message .= "--".$separator.$eol;
$message .= "Content-Type: application/pdf; name=\"".$fileName."\"".$eol;
$message .= "Content-Transfer-Encoding: base64".$eol;
$message .= "Content-Disposition: attachment".$eol.$eol;
$message .= $attachment.$eol;
$message .= "--".$separator."--";
if (mail($to, $subject, $message, $headers)){
$action = 'action=Receipt%20Sent';
header('Location: ../index.php?'.$action);
}
else {
$action = 'action=Send%20Failed';
header('Location: ../index.php?'.$action);
}
I have been using TCPDF for a short amount of time now to generate PDF files from forms. It works quite well and that part of the PHP has not changed. Now I want to send those PDF files to my email account.
The emailing is actually working with this coding and attaching a PDF. The issue is that it is simply a blank PDF at rough 100 bytes in size. Which of course is not a valid PDF nor does it have anything to do with the responses from the form.
I am really not familiar with the attaching of files to an email in PHP and any help resolving this issue would be greatly appreciated.
Update
Since it seems like several people are looking at this still I will post my current solution. It involves downloading PHPMailer as suggested below. I have started at the output line for TCPDF.
$attachment = $makepdf->Output('filename.pdf', 'S');
SENDmail($attachment);
function SENDmail($pdf) {
require_once('phpmailer/class.phpmailer.php');
$mailer = new PHPMailer();
$mailer->AddReplyTo('reply#to.ca', 'Reply To');
$mailer->SetFrom('sent#from.ca', 'Sent From');
$mailer->AddReplyTo('reply#to.ca', 'Reply To');
$mailer->AddAddress('send#to.ca', 'Send To');
$mailer->Subject = 'Message with PDF';
$mailer->AltBody = "To view the message, please use an HTML compatible email viewer";
$mailer->MsgHTML('<p>Message contents</p>'));
if ($pdf) {$mailer->AddStringAttachment($pdf, 'filename.pdf');}
$mailer->Send();
}
You have two choices. You can save the PDF to a file and attach the file or else output it as a string. I find the string output is preferable:
$pdfString = $pdf->Output('dummy.pdf', 'S');
The file name is ignored since it just returns the encoded string. Now you can include the string in your email. I prefer to use PHPMailer when working with attachments like this. Use the AddStringAttachment method of PHPMailer to accomplish this:
$mailer->AddStringAttachment($pdfString, 'some_filename.pdf');
I tried several alternatives. Only way that worked was when I saved the PDF to a folder and then email it.
$pdf->Output("folder/filename.pdf", "F"); //save the pdf to a folder
require_once('phpmailer/class.phpmailer.php'); //where your phpmailer folder is
$mail = new PHPMailer();
$mail->From = "email.com";
$mail->FromName = "Your name";
$mail->AddAddress("email#yahoo.com");
$mail->AddReplyTo("email#gmail.com", "Your name");
$mail->AddAttachment("folder/filename.pdf"); // attach pdf that was saved in a folder
$mail->Subject = "Email Subject";
$mail->Body = "Email Body";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message sent";
}
echo 'sent email and attachment';

Categories