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

56 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 πŸ˜€ 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

comon!! google can do it for you πŸ™‚
http://phpmailer.codeworxtech.com/index.php?pg=sf&p=dl

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

8 03 2010
Sandy

Thank you for the effort. I am new at this and after running the pear.php I copied all the fies, but I get the following errors

Warning: include_once() [function.include]: Failed opening ‘Mail.php’ for inclusion (include_path=’.:/usr/lib/php:/usr/local/lib/php’)

Warning: include_once(Mail_Mime/mime.php) [function.include-once]: failed to open stream: No such file or directory

Any help would be appreciated

10 04 2010
How To Tighten Your Vagina

Many thanks to WordPress for such a great blog & free blog hosting.

24 05 2010
jignesh

Sorry the server was unable to upload the files…

Can any one help i am getting this err

16 06 2010
My Clicker Auto clicker

Thanks a lot for your article ! Its great ! πŸ™‚

6 07 2010
Ion

Thank You

30 07 2010
Ypho

Thanks for the code, some small errors, but fixed it!

30 07 2010
Akil M Shaikh

Thanks A Lot……… You Save My Day………..!!!

31 07 2010
shaffy

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

18 08 2010
denny

thanks mate, just the info I was looking for

20 09 2010
Shahbaz Ahmed

Hello Plz Can Any Body tell me how to find classes.mailer.php. Plz i need help to make a forn email with images attachment. Any help will b your kindness , my engliajs is not good. so plz can any body help me to make me a form of email with images attachment. plz it a request reply me @ shabaz12@hotmail.com
Plz

26 01 2011
Helen

Hi, excellent code, but I keep getting the following error:

Mailer Error: The following From address failed: helen@postle.co.uk

it doesn’t matter what from address I put in, any ideas?

26 01 2011
Helen

OK, doesn’t matter, I’ve figured it out, I left out the line
$mail->IsSMTP();
and now its working

once again, great code

8 05 2011
28 06 2011
Brad

I keep getting this “PHP Error Message”:

Fatal error: require() [function.require]: Failed opening required ‘/class.phpmailer.php’ (include_path=’.:/usr/lib/php:/usr/local/lib/php’) in /home/a1832526/public_html/contact.php on line 2

I added the ‘/’ before class.phpmailer.php as this got rid of the second error message, very simiolar to the first.
I have added a php.ini file with this in:

include_path = “.:/usr/lib/php:/usr/local/lib/php:/home/a1832526/public_html/phpmailer”;

AND I have also tried this:

include_path = “.:/usr/lib/php:/usr/local/lib/php:class.phpmailer.php”;

I know that last one was completely wrong, but i thought it was worth a try πŸ˜€

anyway, help with this would be great, just started with php email forms. I was fine until i needed to add an attachment.

29 06 2011
Brad

Okay, nvm i have it now

11 03 2013
keith

do you remember what the fix was? I am having the exact same problem.

25 08 2011
29 08 2011
allegati multipli in form

[…] Segui questo tutorial basato sulla classe PhpMailer, dovresti risolvere abbastanza velocemente. […]

3 09 2011
Jhabpazv

I’ll put him on teen babysitters nude qios

23 09 2011
Dixgzret

Have you got any experience? Tiny Lolitas
9517

13 10 2011
ramses

hi! i dont get any error… the image it’s up but not attached on mail.

i am missing something? any extra configuration here?
i just dont get any error 😦

16 11 2011
Jaume Bitterhoff Gatius

I had to modify via trial/error so i could manage it to work, and i found that in your code you check the ATTACHMENTS array when you are going to send the mail, but you must check the newly created FILES.
So i’ve changed this line:

foreach($attachments as $key => $value) { //loop the Attachments to be added …

for this line:

foreach($_FILES[images][name] as $key => $value) { //loop the Attachments to be added …

..and now it works ok!

9 12 2011
Yhmipfsm

Will I be paid weekly or monthly? Preteens Nn Models
bopbbi

26 04 2012
Godwin

Your tutorial is great and well explained. i never get tired reading your works. Thanks man.

27 05 2012
site

The design for the blog is a tad off in Epiphany. Nevertheless I like your weblog. I may have to install a normal web browser just to enjoy it.

23 12 2012
visit website

I seriously love your site.. Pleasant colors
& theme. Did you make this website yourself?
Please reply back as I’m trying to create my own personal blog and want to learn where you got this from or just what the theme is called. Cheers!

7 08 2014
ganaysa

Thank you for the instructions !

Leave a comment