Valhalla Legends Forums Archive | Web Development | [PHP] Auto Emailer With Attachements

AuthorMessageTime
InSeCuRe
I have a question that is bugging the crap out of me.  I found a source on php.net about sending emails with attachments.  I got it to work just fine and had no problems with it when I go to the file on my web server.

[CODE]
<?php

require_once 'vars.php';

//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: $from\r\nReply-To: $from";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents($attachment)));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<?php echo $message; ?>

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<?php echo $message; ?>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/txt; name=<?php echo $saveas; ?>
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail($to, $subject, $message, $headers);
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
[/CODE]

BUT if I have an include or require or I put it inside a function and try calling the function or I include it in the current function... It doesn't work and it tells me mail failed.

[CODE]
function addtoFile() {
  $myFile = "./list/test.txt";
  $fh = fopen($myFile, 'w') or die("can't open file");

  $query = mysql_query("SELECT * FROM catrequest WHERE new = '1' ORDER BY lastname ASC, firstname");
    while($row = mysql_fetch_array($query)) {
    $stringData = $stringData . $row['lastname'] . ',' . $row['firstname'] . ',' . $row['address1'] . ',' . $row['address2'] . ',' . $row['city'] . ',' . $row['state'] . ',' . $row['zip'] . "
";
    }
    fwrite($fh, $stringData);
    include("./email.php");
}
[/CODE]


EDIT to include vars.php.

[CODE]
<?php

/* Global Database Variables */
$db_host  = 'localhost';    // Database Server //
$db_name  = 'cia_****';  // Database Name //
$db_user  = 'cia_****';  // Database Username //
$db_pass  = '****';      // Database Password //
/* ENDS Global Database Variables */


/* Global Email Variables */
$to = 'myemail@domain.com'; //define the receiver of the email
$from = 'fake@email.com';
$subject = 'Test email with attachment'; //define the subject of the email
$message = '<h2>Hello Jon!</h2><p>This is something with <b>HTML</b> formatting and an <b>attachment</b></p>';
$attachment = './list/test.txt';
$saveas = 'mailinglist.txt';
/* ENDS Global Email Variables */

/* Global Catalog Variables */
$minbatchnum = 0;
/* ENDS Global Catalog Variables */
?>
[/CODE]

Does anyone have any ideas what would cause this and possibly a solution to fix it?  As you can probably tell the main reason I would like this to work w/o having to go to the page myself would be because I would like the auto mailer to be Automatic.

Also, I have tried setting up a pipeline in Cpanel 11 and sending an email to a specific account and having it pipeline to the file and that doesn't seem to work as I don't get an email that way.

Thank you for any possible help.
May 29, 2007, 12:34 AM
rabbit
*sigh*
It helps to understand what's going on in a script before you try to use or modify it.
May 29, 2007, 1:40 AM
InSeCuRe
Um... expect I know whats going on.  Its doing what I did a search for... its sending an email WITH an attachment, which there isn't a whole lot of documentation on.  I changed the source just enough to list the variables in there instead of the information being built in.  And the reason I used the source... and trust me I am around here a enough just don't post very often is because and I quote some people on the forums.  "Why reinvent the wheel."  And I do believe the question was does anyone have a solution, not have a comment to make w/o giving any ideas.  I'm sorry but there is no reason to say something unless your willing to help.

Not to mention the documentation on the source isn't that bad.  Its pretty decent to understand and my problem doesn't lie with the source ... it lies in the fact that I can't use the source in anything but a php file that you must view in the browser to get it to work, which doesn't make sense to me.
May 29, 2007, 2:17 AM
rabbit
It doesn't make sense because you have no idea what the script is DOING.  You know what the end result is, but you don't have a damned clue how it gets there.  Learn PHP, then revisit this script.
May 29, 2007, 12:11 PM
InSeCuRe
How the hell are you going to tell me that I don't know PHP?  I have only been working with it for years?  You need to keep your mouth shut when you don't know what your talking about.  Quiz me on any part of the code and I will respond when I get home  from work....
May 29, 2007, 12:59 PM
CrAzY
Insecure,

First off, your name 'Insecure' is making me afraid of dealing with you and emails, but I guess thats life ;).

Since I'm not a dick like rabbit, I think I may know your problem. 

Since you are putting this page on your website, maybe you are including this page onto another page.  For example: are you using index.php?page=emailpage?  If so, you probably are trying to include vars.php or whatever it is called more than once.  This can create complications. 

Another debugger I've had to tackle is having a function declared in two different places.  In PHP i don't believe there is any over riding, so make sure that the function or whatever you are declaring is only stated once!  Dont have something included on two pages where one of those pages includes the second page.

Sorry if this doesn't help but I'm just trying to give you some insight.

PS: rabbit, your a dick.

Tim
July 3, 2007, 2:17 PM
rabbit
CrAzY, I'm a dick.

That aside, he doesn't know how the script works, and he's still trying to use it.  You don't know how it works either, so stop trying to help him (your "fix" wouldn't work anyway).
July 3, 2007, 2:40 PM
CrAzY
Rabbit,

I didn't even read his script because I don't want to waste my time.  I was just talking about errors that sound similar to what have happened to me in the past.  And if I’m not mistaken, I think I taught you VB or PHP 3-5 years ago.  Don't walk around acting like you own the place and thinking you are "god" of programming.  The purpose of a Forum is to share discussions about topics in order to help and inform somebody.  Not to tell people they are ignorant for trying to learn something.  Everybody has a different style of learning, that is what makes people unique.  Not everybody is as old as you and has as much experience.  Something that this kid has that you don't is maturity.

Besides, even if my answer isn't correct, it doesn't hurt to attempt to answer a question.
July 3, 2007, 2:57 PM
Invert
I'm here and reading this.
July 3, 2007, 4:28 PM
rabbit
[quote author=CrAzY link=topic=16739.msg170660#msg170660 date=1183474662]And if I’m not mistaken, I think I taught you VB or PHP 3-5 years ago.[/quote]Rofl :P  You are mistaken.  I tought myself all the programming I know.
July 3, 2007, 6:14 PM
CrAzY
[quote author=rabbit link=topic=16739.msg170669#msg170669 date=1183486478]
[quote author=CrAzY link=topic=16739.msg170660#msg170660 date=1183474662]And if I’m not mistaken, I think I taught you VB or PHP 3-5 years ago.[/quote]Rofl :P  You are mistaken.  I tought myself all the programming I know.
[/quote]
My point exactly.
July 13, 2007, 5:20 PM
rabbit
How is that your point at all?  You said, and I quote[quote]I think I <verb> you <a couple possibilities> <some indeterminate amount of time> ago maybe.[/quote]Another way of displaying what you said is[quote]<Outrageous claim that is a blatant and outright lie>.[/quote]

If your point is that you're wrong, then yeah, that's your point.  Otherwise, you're wrong.

[edit]
Please stop trolling you jackass.
July 13, 2007, 10:57 PM
CrAzY
My point was you're immature.  Even if I was wrong about anything, doesn't change the fact that I'm not criticizing him.
July 16, 2007, 5:42 PM
rabbit
[quote author=CrAzY link=topic=16739.msg171039#msg171039 date=1184607752]
My point was you're immature.  Even if I was wrong about anything, doesn't change the fact that I'm not criticizing him.
[/quote]You never said that was your point, thus it wasn't your point.  And criticism is useful.  You're not helping him by telling him something that might fix a script, even though he doesn't know how the script works.
July 16, 2007, 6:29 PM
InSeCuRe
Rabbit, can you explain to me why you think I don't know anything about PHP?  Or are you simply stating that I don't know anything about that script?  If you are saying I don't know anything about that script you would be a genius.  Want to know why?  ... Well it might be because I openly admitted to finding the source on a website?  I have seen, I believe it was Invert state on this forum a couple times along with others (sorry if it wasn't him exactly...) "Why reinvent the wheel?"  Why do I HAVE to create something that is already out there?

If your simply just stating why ask questions unless I know the script.  Well, I know it enough to get it working, somewhat.  But why would I have a question if I knew the answer already?  In your logic there would be no room to "learn", because there would be no room to ask questions.

So, why are you criticizing me for asking a question?
July 17, 2007, 2:38 AM
rabbit
I never said write it yourself, I said understand it.  Look into output buffering and you MIGHT get an idea of what the script is doing.
July 17, 2007, 2:55 AM
JoeTheOdd
[quote author=rabbit link=topic=16739.msg170984#msg170984 date=1184367445]
Please stop trolling you jackass.
[/quote]

Please stop trolling you jackass.
August 1, 2007, 6:31 AM
Quarantine
[quote author=Joe[x86] link=topic=16739.msg171312#msg171312 date=1185949898]
[quote author=rabbit link=topic=16739.msg170984#msg170984 date=1184367445]
Please stop trolling you jackass.
[/quote]

Please stop trolling you jackass.
[/quote]

If he truly is a troll (which I doubt), you're just feeding him.
Sort of silly of you to quote Kp and yet still feed the "troll"

way to fail.
August 1, 2007, 8:51 PM
-MichaeL-
as for the reasons your code doesn't work is the way your calling it and not setting any data! as your email.php i assume is
[code]
<?php

require_once 'vars.php';

//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: $from\r\nReply-To: $from";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents($attachment)));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<?php echo $message; ?>

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<?php echo $message; ?>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/txt; name=<?php echo $saveas; ?>
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail($to, $subject, $message, $headers);
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
[/code]

try this instead make a file named sendemail.php and put in the following code.

[code]
<?php
Function SendEmail($to, $from, $message, $attachment) {
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: $from\r\nReply-To: $from";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents($attachment)));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<?php echo $message; ?>

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<?php echo $message; ?>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/txt; name=<?php echo $saveas; ?>
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail($to, $subject, $message, $headers);
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
return $mail_sent ? "Mail sent" : "Mail failed";
}
?>
[/code]

then make email.php

[code]
<?php
echo SendEmail($"myemail@test.com", "their@test.com", "Here is your file...., "path to file and its name");
?>
[/code]

This way it should work, i don't have the time to test it, but this way you wont need to worry about settings any vars from any other file and can change anything each time you call it.

i gather from this
[code]
function addtoFile() {
  $myFile = "./list/test.txt";
  $fh = fopen($myFile, 'w') or die("can't open file");

  $query = mysql_query("SELECT * FROM catrequest WHERE new = '1' ORDER BY lastname ASC, firstname");
    while($row = mysql_fetch_array($query)) {
    $stringData = $stringData . $row['lastname'] . ',' . $row['firstname'] . ',' . $row['address1'] . ',' . $row['address2'] . ',' . $row['city'] . ',' . $row['state'] . ',' . $row['zip'] . "
";
    }
    fwrite($fh, $stringData);
    include("./email.php");
}
[/code]

you want to send it to anyone listed in your mysql db. you just need to make a few changes to email.php which should be easy
September 18, 2007, 2:51 AM
Camel
[code]
function addtoFile() {
  $myFile = "./list/test.txt";
  $fh = fopen($myFile, 'w') or die("can't open file");

  $query = mysql_query("SELECT * FROM catrequest WHERE new = '1' ORDER BY lastname ASC, firstname");
    while($row = mysql_fetch_array($query)) {
    $stringData = $stringData . $row['lastname'] . ',' . $row['firstname'] . ',' . $row['address1'] . ',' . $row['address2'] . ',' . $row['city'] . ',' . $row['state'] . ',' . $row['zip'] . "
";
    }
    fwrite($fh, $stringData);
    include("./email.php");
}
[/code]

1) Initialize your freakin variables (stringData)! If you just so happen to have PHP set up so that all variables are global, and so request variables are loaded in to global variables (both of which are incidentally not the default values), your test.txt is about to get hosed. I'm sure that's not a security risk in your case, but it's something everyone should required to be aware of before being allowed to write PHP.

2) Don't concatenate strings when you don't have to; it's expensive. Instead, put your fwrite() in the loop. Yes, I'm nit-picking; deal with it.
September 18, 2007, 8:05 AM
rabbit
That's an easy exploit, actually.  As Camel said, if all variables are global, someone could screw with the value of $stringData by passing a value along in GET.

Also, if you ARE going to concat, at least do it in a non VB way: .=
But concat vs fwrite doesn't matter too much, since 1) there's not very much data actually being handled and 2) your function is already inefficient.

And lastly, die()?  Write some error handlers...

And post-lastly, I'm being picky, but I like to stick to standards:
SELECT * FROM `catrequest` WHERE `new` = '1' ORDER BY `lastname` ASC, `firstname`
September 18, 2007, 1:47 PM
Camel
[quote author=rabbit link=topic=16739.msg172904#msg172904 date=1190123264]
That's an easy exploit, actually.  As Camel said, if all variables are global, someone could screw with the value of $stringData by passing a value along in GET.

Also, if you ARE going to concat, at least do it in a non VB way: .=
But concat vs fwrite doesn't matter too much, since 1) there's not very much data actually being handled and 2) your function is already inefficient.

And lastly, die()?  Write some error handlers...

And post-lastly, I'm being picky, but I like to stick to standards:
SELECT * FROM `catrequest` WHERE `new` = '1' ORDER BY `lastname` ASC, `firstname`
[/quote]

String concatenation requires allocating a new block of memory that's the size of the two things being concatenated, and then copying memory from both buffers to the new one. Doing lots of tiny concatenations to a large string is extremely inefficient when compared to fwrite().

What's wrong with die()? I use it all the time; it'd be nice if you gave yourself more information about what's going on, such as the function you're in, or the file that failed to open.
September 20, 2007, 4:02 PM
rabbit
http://us2.php.net/manual/en/function.set-error-handler.php

You can get all the info you want by doing something like that (the example).  Personally, I use a wrapper system and I manually handle most errors (IE: everywhere you could use die()).  I used to use die(), but I got annoyed with it very quickly.

For what he's doing, using concatenation isn't that bad.  If he's writing code for some big site where the function is called a fewhundred times a minute, he should rethink his function.
September 20, 2007, 11:07 PM
Camel
Infrequent use is not a good argument for bad algorithmic design.
September 21, 2007, 4:47 AM

Search