Question

Send Mail from File contents HTML or TXT as needed -- Geir??

Asked by: sciwriter

Geir, I hope you (and others) are there to help me with this.

I have a mail.php that gets all kinds of variable from an input form -- it needs to process those variables, and construct a complete HTML file of an order, ready to email to a recipient.  It cannot OUTPUT any text to the screen, it just needs to compose a file layout.  Assume I can do that, and call it file1.php, for the people who will receive HTML email. I also have to translate that HTML file into a TXT file ( aaarrgghh!!) for the people who refuse to accept HTML, so assume that non-html file is called file1.txt.

Now, Using the PHP MAIL function, as you described in this previous thread: http://www.experts-exchange.com/Web/Web_Languages/PHP/Q_21462397.html

I need to compose a "global email" routine that will take into account both the HTML file, for those who can/will receive it, versus the file1.txt file, for those who stubbornly refuse to handle HTML in their email.

Please post a complete routine to choose which file is relevant, and how to read in each file to mail() it to the recipient.  I am not experience or confident in PHP mail, since it seems to be focussed on a trivial "msg" concept that cannot handle a total mail file, or different email sending options, based on user ideas.

Thanks for your help Geir, and any others who want to conribute to an expansion of the "mail" function.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-06-22 at 21:03:10ID21467881
Tags

php

,

mail

,

html

,

send

Topic

PHP Scripting Language

Participating Experts
4
Points
500
Comments
22

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. PHP Application Framework Ideas/Concepts
    I am a developer of large-scale PHP web apps and I am interested in creating my own application framework because I feel most of the current ones out there are far too complex in design and “dumbed down” for the end user. Not to mention the lack of OOP and design-documentati...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: geir_andersenPosted on 2005-06-22 at 21:26:00ID: 14281456

I'll do my best to help you.
I'll have to write some code a bit later (I'm just not really awake yet) and post here, but I'll give you a pointer..
You don't need to create files. We just use variables in the script to hold both the html email-message and text email-message.

>>Please post a complete routine to choose which file is relevant, and how to read in each file to mail() it to the recipien
Well, PHP can't decide wheter an end-user can accept html or text email messages.
The only way to do that is to make recipients sign up and choose what format they want mail in. Then store that in a database and send the email type based on info from the database.

If you don't know what each user can accept, then you have to revert to sending in one format, I'm afraid.

Also, I/we can't write functioning code ready for you to use since we don't know how your form looks, how you want the mail to look or anything for that matter.. But I'll write and example HTML form with a few fields, then some PHP code that'll extract variables from that HTML form and send that in an email, so you get an idea.

-Geir

 

by: sciwriterPosted on 2005-06-22 at 21:44:02ID: 14281520

Geir, thanks for replying, and please, get some sleep, then reply :))

Can't ask the user for their mail preferences, since most don;t know.  So assume we have to send MIME for HTML and TXT and they receive whatever their browser wants to get ....

As for the content of the mail, just ASSUME I will create a complete HTML file (and a complete TXT file) called "file1" (either .html or .txt) to be read in as $msg.  I have no problem composing those files, what I am not sure of is the code to "send-mail" those files using PHP.  The files are just what the user will see on screen, nothing more, nothing less, so I'm not sure how to send it.  

Thanks for replying, I MUCH appreciate it !!!!  How is the weather in N.E. Europe ??  In the west U.S here, it is hot and dry, too hot, and there are many bushfires -- definite proof of global warming !!!   Cheers....

 

by: hernst42Posted on 2005-06-22 at 23:02:57ID: 14281791

If you want to send both HTML and plaintext-mails use http://phpmailer.sf.net for that. If you have the HTML-text you can get a plain-text via the striptags function in php.

like the following
$body = file_get_contents(....)

$mail = new PHPMailer();
$mail->Body    = $body;
$mail->AltBody = striptags($body);

 

by: sciwriterPosted on 2005-06-22 at 23:17:36ID: 14281837

hernst42 -- standard Linux shared hosting, don't know if any add-on modules can run.  I saw somwhere, a routine to just do the two MIME types, HTML and TXT together, can't find it now -- any ideas on in-line send of both as different MIME types, which lets the user's browser/mail client decide what to accept??

I can only "striptags()" to a certain point -- I need to preserve the "proportional font" or "variable pitch font" because that is the only way the TXT file will come out lined up correct.  So striptags may not work.  Ideas?

 

by: hernst42Posted on 2005-06-22 at 23:32:09ID: 14281872

With plain text-files you can't do any formating with fonts. That is only possible with HTML- or RTF mails. If you your are using phpmailer the clients browser/mailer take either the plain text or the HTML depending on the user's preference.

You can download phpmailer and include it in your php-directory (there is no need to bother your webhoster). Its completly written in PHP.

 

by: geir_andersenPosted on 2005-06-23 at 00:18:32ID: 14282007

I second hernst42's suggestion about using PHPMailer for your need.
The documentation and examples found on their site should make it straightforward to start using.
I've never personally used it before, so I have no experience to share I'm afraid.

-Geir

 

by: sciwriterPosted on 2005-06-23 at 09:59:38ID: 14286097

I already looked at PHP mailer weeks ago, and yes it is a possibility, but not right now.

I've found that I eventually figure everything out, even the "can't be done"s, like sending a PHP page to a different window on the page.  I come to this TA to help speed up the process. I think for right now I'm not going to bother with the unformatted text file, just do the HTML and get that working first.

So Geir, in a previous question, I think you showed how to open another file and read it into a $msg variable and mail it.  Can you go over that again, please, in the following context --

The format file, say called 'htmlmsg.php' needs to be read into a file that will insert the values into its variables -- $name, $address, $city, $state, $zip -- and so forth.  The htmlmsg.php will have those variables names in it, just as listed, so the job of the reading file (which holds the VALUES of those variables in it's page), will be to (1) read in the other file (2) substitute values for the variables, then (3) mail it to two addresses, $sender and $receiver.

Thae point of the "format file" is to keep the format of the message separate from the PHP code, for obvious reasons.  You already gave much of the code in a previous question, maybe you would be kind enough to pull it together here ...  Any further details needed, just ask .... and many thanks ....

 

by: sciwriterPosted on 2005-06-23 at 10:20:51ID: 14286346

Looking back over your answers on the prev. question, I might be able to get a lot of it from that alone, but anything else you can add would be great, especially about inserting the values in the variables.  Thx.

 

by: geir_andersenPosted on 2005-06-23 at 10:22:36ID: 14286363

OK here is an example:

say you have the following two files:
names.txt (containing variable names, one pr line)
values.txt (containing variable values, one pr line)
AND
line 1 of values.txt is the value for the variable named on line 1 of names.txt

--contents of names.txt--
banana
apple
pear
--contents of values.txt--
1
2
3

You can use the following php script to get it:
<?
$variable_names = "names.txt";
$variable_values = "values.txt";

$f1 = file_get_contents($variable_names);
$names = explode("\n", $f1);

$f2 = file_get_contents($variable_values);
$values = explode("\n", $f2);

for ($i=0;$i<count($values)-1;$i++){
        echo "I have {$values[$i]} {$names[$i]}<br>";
}

?>

This would output:
I have 1 banana
I have 2 apple
I have 3 pear

Is this along the lines you were thinking?

-Geir

 

by: sciwriterPosted on 2005-06-23 at 13:26:58ID: 14288157

No Geir, sorry for not explaining myself clearer.  It could well be that PHP will automatically do this, so I don't have to replace any $variables with "values".

In the layout page, I have a whole series of -- <?php echo $Email; ?> <?php echo $Name; ?>

but those variables are not gotten by that page at all.  The emailing.php page has the values of the variables  and when I "read in" the layout page into a single variable $msg in the emailing page (as you suggested in the previous Q) -- will those values be echoed correctly, or do I have to do something special to insert them?

On a related issue, There are about 20 such variables, $Name, $Address, etc.  in the emailing.php page -- is there a simple way to transfer them to another page in a PHP array?  I can put them all in a FORM and send them that way, but it would be a lot simpler to pass the next page one PHP array containing all the $Vars.

 

by: geir_andersenPosted on 2005-06-23 at 13:46:10ID: 14288365

OK, something like this?

--emailing.php--
<?
$name = "sciwriter";
$section = "PHP";
?>

--output.php--
<? echo $email; ?>
<? echo $section; ?>

To make the variable values known in output.php simply:

--output.php--
<?
include("emailing.php");
?>
<p><? echo $email; ?></p>
<p><? echo $section; ?></p>


That would print out:
sciwriter
PHP

-Geir

 

by: sciwriterPosted on 2005-06-23 at 14:10:56ID: 14288655

Yep, that's kind of what I suspected -- use include instead of reading the file in.  That makes life a WHOLE lot simpler, because when I find out how to split the email (MIME is based on the header sent in the mail), I can do a conditional include -- html or txt, depending on MIME type.

But I still have to get the ENTIRE formatted file "htmlmail.php"  -- read into a single variable, "$msg", in order for the mail module to send it, correct?  I see this as maybe a limitation of that mail() routine, that you can't pass it an entire file name, rather than a $msg -- but that's probably because I don't see a way yet to get around it.  Any ideas, using "include()", as to how to get the included file ready to email?

Thanks again...

 

by: sciwriterPosted on 2005-06-23 at 14:59:48ID: 14289296

hernst42 if you are still there, do you want to take a stab at answering the "on a related issue" Q above?

 

by: geir_andersenPosted on 2005-06-23 at 15:11:28ID: 14289441

simple:
a tested and working example:

--values.php--
<?
$name = "sciwriter";
$section = "PHP";
?>
--output.php--
<?
include("values.php");
?>
<p>Name...: <? echo $name; ?></p>
<p>Section.: <? echo $section; ?></p>


Then the "magic" php script:

<?
$php_path = "/usr/bin/php";  
//path above is the complete path to where the php "executable" is located (use: find / -name php   in linux to find it
$the_file = "output.php";

$msg = "{$php_path} -f {$the_file}";
?>

Now the variable $msg will contain:
<p>Name...: sciwriter</p>
<p>Section.: PHP</p>


Then you can mail it using the mail function you decide to use.

-Geir

 

by: sciwriterPosted on 2005-06-23 at 15:19:06ID: 14289504

GREAT !!

<?
$php_path = "/usr/bin/php";  
$the_file = "output.php";
$msg = "{$php_path} -f {$the_file}";
?>

That is the crucial part I was missing.  Let me give it a shot and I will get back.  Many thanks ...

 

by: sciwriterPosted on 2005-06-23 at 17:00:32ID: 14290058

Geir -- quick Q, as I develop this -- need to send to at LEAST 2 email addresses --

So in -- mail("to_address", "subject", $file_contents) or die ("Unable to send the mail");
how do you get 2-3 email addresses in the "to_address"?
And rather than die()  -- how do you send this as an error to a message in the file itself (i.e. don't want to terminate the PHP file, just want to tell the user there was a problem.)   Don't see this in the PHP docs.

Thanks for your help ....

 

by: geir_andersenPosted on 2005-06-24 at 01:54:18ID: 14292028

Hi.
To send to more recipients I use this code:
<?
$recipients = array("
                \"Recipient 1\"<email@domain1.com>,
                \"Recipient 2\"<email@domain2.com>,
                \"Recipient 3\"<email@domain3.com>
");

$msg = "Hi\nThis is a test";

$headers  = "From: \"Geir Andersen\"<my@address.com>\n";
$headers .= "Reply-To: my@address.com\n";
$headers .= "Content-Type: text/plain; charset=iso-8859-1\n";

foreach ($recipients as $recipient) {
        mail($recipient, "This is a test", $msg, $headers) or die("Could not send mail.");
}

?>

-Geir

 

by: hernst42Posted on 2005-06-24 at 06:03:26ID: 14293112

you can also use output-buffering to catch the putput of an html-page like:

ob_start();
include 'htmlmail.php';
$text = ob_get_contents();
ob_end_clean();


See http://de3.php.net/manual/en/ref.outcontrol.php

 

by: JKlattePosted on 2005-06-27 at 03:46:15ID: 14307102

The mailing part I believe I described pretty thoroughly in Q_21469204 - the example there should work perfectly.
As for your HTML/TXT file inclusion, I'd simply go at it like this:

1 - The main mail.php script gets all kinds of variables from a form.
2 - You include a mailcontent.php file that contains two string variables: $HTMLmail and $PLAINmail. By including the file from mail.php, the existing variables are parsed into the mailcontent strings. They can be written down in HEREDOC syntax, so there's no echo's interrupting your code. Example:

//mailcontent.php:

$HTMLmail =<<<ENDOFHTMLMAIL
<HTML>
<BODY>
My name is $name.
</BODY>
</HTML>
ENDOFHTMLMAIL;

$PLAINmail =<<<ENDOFPLAINMAIL
My name is $name.
ENDOFPLAINMAIL;

(i.e. the contents of the $name variable that has been posted to the mail.php script is now part of the strings.)

3 - You send the mail as multipart MIME with your mail.php script, so the mail contains both plain text and HTML formatted text. (see Q_21469204)

 

by: sciwriterPosted on 2005-06-28 at 14:57:04ID: 14323528

Geir, hernst42 and JKlatte -- I apologize for the delay in responding, but with my account messed up, I could not till now.  

Geir, although your 3:11 PM "working example" gave the overall layout I needed, the crucial part --
$msg = "{$php_path} -f {$the_file}";
did not actually work -- all I got in $msg was the literal string of PHP directory + file path -- no contents.

It was Hernst42's code --
ob_start();
include 'htmlmail.php';
$text = ob_get_contents();
ob_end_clean();

That actually DID get the HTML file into the $msg variable correctly.  Thanks hernst42, nice work, friend.

Finally JKlatte's heredoc is a valuable other way to pipe the MIME/split input into the stream.

Consequently, I am splitting points among you as fairly as I can.  Hope this is OK.  This has been a great question with great input.  If I had 5000 points to split on this Q, I would do it.

Lastly, you probably won't see me here any more.  I've enjoyed the few bright experts who have replied to my questions, but the others are too much to deal with, sorry.  You can always contact me if you wish.

Best of luck to you three, and many thanks for contributing so much to the questions I've asked in PHP.

 

by: geir_andersenPosted on 2005-06-28 at 22:49:27ID: 14325587

you are absolutely right, syntax error on my part.
the line should be:
$msg = shell_exec("{$php_path} -f {$the_file}");
sorry about that.

Thanks for the points

-Geir

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...