Sending email attachments in PHP Using phpmailer class !

10 01 2007

A friend of mine asked me for such a script that will attach Jpg Images and send it to a particular email , so i started one from scratch .
The Basic idea is to upload the images to the server and then use phpmailer class to attach the files and send them .
The files can be found @Zainals
PHPMailer Class can be found @ http://phpmailer.sourceforge.net/
To Learn more about file uploads visit Plus2Net

Make sure you have a directory called upload and set its chmod to 777 .

oh well , sharing is caring eyh ?

first of all we need to setup the form that will interface with the users , i have found this multi browse code @ : Plus2Net
<?php
$max_no_img=5; // Maximum number of images value to be set here
echo "<form method=post action=attach.php enctype='multipart/form-data'>";
for($i=1; $i<=$max_no_img; $i++){
echo "<tr><td>Photo $i: </td><td>
<input type=file name='images[]' class='bginput'></td></tr>";
}

?>

And now for the PHP Part , excuse the sloppness :
<?php
require("class.phpmailer.php");
//Variables Declaration
$name = "the Submitter";
$email_subject = "Images Attachment";
$Email_msg ="A visitor submitted the following :\n";
$Email_to = "you@yourSite.com"; // the one that recieves the email
$email_from = "someone@someone.net";
$dir = "uploads/$filename";
chmod("uploads",0777);
$attachments = array();
//
checkType();
//
//------Check TYPE------\\
function checkType() {
while(list($key,$value) = each($_FILES[images][type])){
strtolower($value);
if($value != "image/jpeg" AND $value != "image/pjpeg" AND $value != "") {
exit('Sorry , current format is <b>'.($value).'</b> ,only Jpeg or jpg are allowed.') ;
}
}
//
checkSize();
//
}
//-------END OF Check TYPE--------\\
//
//---CheckSizeFunction ---\\
function checkSize(){
while(list($key,$value) = each($_FILES[images][size]))
{
$maxSize = 5000000;
if(!empty($value)){
if ($value > $maxSize) {
echo"Sorry this is a very big file .. max file size is $maxSize Bytes = 5 MB";
exit();
}
else {
$result = "File size is ok !<br>";
//
}
//
}
//
}
uploadFile();
//
}
//-------END OF Check Size--------\\
//
//==============upload File Function============\\
//
function uploadFile() {
global $attachments;
while(list($key,$value) = each($_FILES[images][name]))
{
//
if(!empty($value))
{
$filename = $value;
//the Array will be used later to attach the files and then remove them from server ! array_push($attachments, $filename);
$dir = "uploads/$filename";
chmod("uploads",0777);
$success = copy($_FILES[images][tmp_name][$key], $dir);
}
//
}
//
if ($success) {
echo " Files Uploaded Successfully<BR>";
SendIt();
//
}else {
exit("Sorry the server was unable to upload the files...");
}
//
}
//
//==== PHP Mailer With Attachment Func ====\\
//
function SendIt() {
//
global $attachments,$name,$Email_to,$Email_msg,$email_subject,$email_from;
//
$mail = new PHPMailer();
$mail->IsSMTP();// send via SMTP
$mail->Host = "localhost"; // SMTP servers
$mail->SMTPAuth = false; // turn on/off SMTP authentication
$mail->From = $email_from;
$mail->FromName = $name;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
$mail->WordWrap = 50;// set word wrap
//now Attach all files submitted
foreach($attachments as $key => $value) { //loop the Attachments to be added ...
$mail->AddAttachment("uploads"."/".$value);
}
$mail->Body = $Email_msg."Name : ".$name."\n";
//
$mail->IsHTML(false);// send as HTML
$mail->Subject = $email_subject;
if(!$mail->Send())
{
echo "Message was not sent <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
//
echo "Message has been sent";
// after mail is sent with attachments , delete the images on server ...
foreach($attachments as $key => $value) {//remove the uploaded files ..
unlink("uploads"."/".$value);
}
//
}
//
?>

I know the that its hard to read the script of this blog , The PHP file is available @ Zainals


Actions

Information

29 responses

11 01 2007
June

Wow. I wish I knew what you were on about but I feel like leaving a comment so hello :)

11 01 2007
Mohammed Zainal

JuNe ,i some times have no idea what i am about so …relax ;)
Hope you enjoyed yer trip .greetings 2 DuSo .

29 01 2007
Diipa Daapa

this is most excellent!

29 01 2007
Mohammed Zainal

cheers Buddy …

26 04 2007
cars

well done mate, good work. I was searching some similar stuff.

13 05 2007
search a car

nice stuff. realy useful.

8 06 2007
vance

Hello there!..I really find this useful…good job!

16 08 2007
Me

Thank you, this is great. Good work.

24 08 2007
Salman

Zainal,

Thanks for sharing such a wonderful script, Can you please suggest or show us a direction, where we can use iframes for upload interaction and returning the errors on the email form, since the current script performs the post display errors on next page. This way the user won’t leave the current page.

Secondly is there anyway we can show a progress bar while performing attachments.

8 09 2007
ravinagar79

Hi yf;ls,;’

28 04 2008
Goncalo

This is brilliant!!! I hope you don’t mind, but i’m trying (yes, trying because for me its hard), to use this attach.php to a swf contact form… any thoughts???
anyone????

11 07 2008
Ahmed Aboughrara

Great Article.
i just want to mention to a bug that could happened to you if you use php6.0 with phpmailer class:
these fucntions:
get_magic_quotes_runtime
set_magic_quotes_runtime

bug

24 07 2008
Michael

I keep getting these errors. Any clues?

Warning: Variable passed to each() is not an array or object in d:\domains\abizgraphics.com\wwwroot\form\pubform_test.php on line 17

Warning: Variable passed to each() is not an array or object in d:\domains\abizgraphics.com\wwwroot\form\pubform_test.php on line 35

Warning: Variable passed to each() is not an array or object in d:\domains\abizgraphics.com\wwwroot\form\pubform_test.php on line 64
Sorry the server was unable to upload the files…

7 11 2008
Ahpiak

That’s obviously because your variable is not an array. Looking at the line where the errors were pointed. Reference to the relevant ones and check if its an array.

Hint: Arrays are declared as hello[], not hello. So you might need something like this ->

20 01 2009
Vortex

Hello,

Im trying to use this script but like the previous user said im getting these errors :

Warning: Variable passed to each() is not an array or object in C:\Inetpub\vhosts\cavendishknights.com\httpdocs\attach.php on line 17

Warning: Variable passed to each() is not an array or object in C:\Inetpub\vhosts\cavendishknights.com\httpdocs\attach.php on line 35

Warning: Variable passed to each() is not an array or object in C:\Inetpub\vhosts\cavendishknights.com\httpdocs\attach.php on line 64
Sorry the server was unable to upload the files…

I dont understand your explination to WHY im getting them could you explain for someone who has no idea what hes doing :D Thanks in advance!

21 01 2009
Jose

Hi i am using this script.
One problem I faced is when i select more than one image for uploading , the program only attaches the first Image to the Email.
I have checke dthe attachment array ad it show all 3 files paths correctly

What may be the issue?

Any help ?

Thanks

3 02 2009
Javier

Hello, I’m new to PHP and I’m getting some errors:

1) Notice: Undefined variable: filename in …[path here]… on line 277

2) Warning: chmod() [function.chmod]: No such file or directory in …[path here]… on line 278
3)
Fatal error: Call to undefined function checkType() in …[path here]… on line 281

At first sight I’ve noticed In the vars definition of the code $filename is undefined, chmod error is called like a function error but on the code “upload/$filename” is not between “()”, function checkType(); is defined below the call so we are calling a function first and defining it later? does this work?

3 02 2009
Javier

Problem at # 2) solved it was a typo, can’t get rid of the others :(

3 02 2009
Javier

Problem at # 1) Solved defining variable $filename = $_POST['images']; now the call to the function is left :(

3 02 2009
Javier

Well no more errors, but files are not being uploaded… I give up!

26 02 2009
Cutty

Good job, but I can’t find and download PHPMailer Class… :(

27 02 2009
Moe
18 03 2009
VF

Has anyone figured out the array errors on lines 17, 35, 64? Like Michael and Vortex, I’m getting these errors, and don’t know how to fix them.

5 04 2009
Alan

thanks very much excellent stuff

8 04 2009
Vlad

Hmmm…. This is really crap code, dude. I’m sorry, but I’d be really embarrassed at publishing this. You are really leading promising PHP developers down the wrong path. How about some OO classes? And using Global vars? WTF?

8 04 2009
moe

Vlad, many thanks for your childish opinion, if you don’t like it leave it, it seems that people like it and it inspired them to write their own code.

I’d say you get your own blog, if you know what a blog is and start writing about some game hacks or about the south beach diet, and make sure you read a lil about http://en.wikipedia.org/wiki/Netiquette

FYI its called OOP, and no its not always necessary to use OOP, we are designers we stick to our lovely lined up codes :) suckerrrrrrrrrr …

25 04 2009
hann

Hello Moe,

Thanks for posting this. I have tried the script and it all works well, other than only one attachment is sent, instead of the multiple attachments in the folder. I also tried the test script that come with phpmailer and the same thing happens. Any clues?

27 04 2009
Jimbo

Hi All,

I’m getting a FATAL ERROR:

Files Uploaded Successfully

Fatal error: Call to undefined function: sendit() in path/to/send.php on line 98

At present, the SendIt() function is called right after the copy command on success,however, the SendIt function is not really initiated or compiled till later in the code. Is this an issue? Any troubleshooting tips are greatly appreciated. Thanks!

2 11 2009
BestFreeAds

Hi,

Excellent post, keep it up.

Thanks

Leave a comment