PHP email

gaptrast

Member
Messages
123
Reaction score
0
Points
16
Hi,

I have made a few websites now, and have used the php include fuction to save time and work.

How can I add a email function ?? I have read things like this, but I do not understand....

My website will be like this:

* Some options
* Some text fields (details, email, etc...)
* (Aviability to upload images)
* Sumbit button


Thanks...
 

cybrax

Community Advocate
Community Support
Messages
764
Reaction score
27
Points
0
There are plenty of tutorials and explinations on around, but for something really quick try this. Just cut and paste and do not forget to change the email address to the one you want to use. The script provides both form validation and has a filter to stop spambots and abusers sending rude messages to you via the form.

It also includes the senders IP address and their computers user agent string.



PHP:
<?php


// OPTIONS - PLEASE CONFIGURE THESE BEFORE USE!

$yourEmail = "yourEmailAddress@someSite.com"; // the email address you wish to receive these mails through
$yourWebsite = "MySite"; // the name of your website
$maxPoints = 4; // max points a person can hit before it refuses to submit - recommend 4


function isBot() {
	$bots = array("Indy", "Blaiz", "Java", "libwww-perl", "Python", "OutfoxBot", "User-Agent", "PycURL", "AlphaServer", "T8Abot", "Syntryx", "WinHttp", "WebBandit", "nicebot", "autoemailspider","Atomic_Email_Hunter/4.0","ContactBot/0.2","ContentSmartz");
	$isBot = false;
	
	foreach ($bots as $bot)
	if (strpos($_SERVER['HTTP_USER_AGENT'], $bot) !== false)
		$isBot = true;

	if (empty($_SERVER['HTTP_USER_AGENT']) || $_SERVER['HTTP_USER_AGENT'] == " ")
		$isBot = true;
	
	return $isBot;
}

if ($_SERVER['REQUEST_METHOD'] == "POST") {
	$error_msg = NULL;

	if (isBot())
		exit("bots not allowed.</p>");

	function clean($data) {
		$data = trim(stripslashes(strip_tags($data)));
		return $data;
	}
	
	// lets check a few things - not enough to trigger an error on their own, but worth assigning a spam score.. 
	// score quickly adds up therefore allowing genuine users with 'accidental' score through but cutting out real spam :)
	$points = (int)0;
	
	$badwords = array("adult", "beastial", "bestial", "blowjob", "clit", "cum", "cunilingus", "cunillingus", "cunnilingus", "cunt", "ejaculate", "fag", "felatio", "fellatio", "****", "fuk", "fuks", "gangbang", "gangbanged", "gangbangs", "hotsex", "hardcode", "jism", "jiz", "orgasim", "orgasims", "orgasm", "orgasms", "phonesex", "phuk", "phuq", "porn", "pussies", "pussy", "spunk", "xxx", "viagra", "phentermine", "tramadol", "adipex", "advai", "alprazolam", "ambien", "ambian", "amoxicillin", "antivert", "blackjack", "backgammon", "texas", "holdem", "poker", "carisoprodol", "ciara", "ciprofloxacin", "debt", "dating", "porn", "link=", "voyeur");
	$exploits = array("content-type", "bcc:", "cc:", "document.cookie", "onclick", "onload", "javascript");

	foreach ($badwords as $word)
		if (strpos($_POST['comments'], $word) !== false)
			$points += 2;
	
	foreach ($exploits as $exploit)
		if (strpos($_POST['comments'], $exploit) !== false)
			$points += 2;
	
	if (strpos($_POST['comments'], "http://") === true || strpos($_POST['comments'], "www.") === true)
		$points += 2;
	if (isset($_POST['nojs']))
		$points += 1;
	if (preg_match("/(<.*>)/i", $_POST['comments']))
		$points += 2;
	if (strlen($_POST['name']) < 3)
		$points += 1;
	if (strlen($_POST['comments']) < 15 || strlen($_POST['comments'] > 1500))
		$points += 2;
	// end score assignments

	if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comments'])) {
		$error_msg .= "Name, e-mail and comments are required fields. \n";
	} elseif (strlen($_POST['name']) > 35) {
		$error_msg .= "The name field is limited at 35 characters. Your first name or nickname will do! \n";
	} elseif (!ereg("^[A-Za-z' -]*$", $_POST['name'])) {
		$error_msg .= "The name field must not contain special characters. \n";
	} elseif (!ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$",strtolower($_POST['email']))) {
		$error_msg .= "That is not a valid e-mail address. \n";
	} elseif (!empty($_POST['url']) && !preg_match('/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i', $_POST['url']))
		$error_msg .= "Invalid website url.";
	
	if ($error_msg == NULL && $points <= $maxPoints) {
		$subject = "Email from your website";

		$message = "You received this e-mail message through your website: \n\n";
		foreach ($_POST as $key => $val) {
			$message .= ucwords($key) . ": $val \r\n";
		}
		$message .= 'IP: '.$_SERVER['REMOTE_ADDR']."\r\n";
		$message .= 'Browser: '.$_SERVER['HTTP_USER_AGENT']."\r\n";
		
		
		
		$message .= 'Points: '.$points;

		if (strstr($_SERVER['SERVER_SOFTWARE'], "Win")) {
			$headers   = "From: $yourEmail \r\n";
			$headers  .= "Reply-To: {$_POST['email']}";
		} else {
			$headers   = "From: $yourWebsite <$yourEmail> \r\n";
			$headers  .= "Reply-To: {$_POST['email']}";
		}

		if (mail($yourEmail,$subject,$message,$headers)) {
			echo ' <p  style="font-size:36px"align="center">Your mail was successfully sent</p>';
		} else {
			echo '<p  style="font-size:36px; color:#FF0000" align="center"> ERROR: Mail NOT Sent </p>';
		}
	}
}
function get_data($var) {
	if (isset($_POST[$var]))
		echo htmlspecialchars($_POST[$var]);
}
if ($error_msg != NULL) {
	echo '<p><strong style="color: red;font-size:36px; ">ERROR: spam filter tripped</strong><br />';
	echo nl2br($error_msg) . "</p>";
}
?>
<form action="a_contact.php" method="post">
<noscript><p><input type="hidden" name="nojs" id="nojs" /> </p></noscript>
	   
        <table width="85%" border="0" align="center" cellpadding="0" cellspacing="0">
          <tr>
            <td class="sidebar_box"><label for="name">Name:</label> </td>
            <td class="sidebar_box" colspan="2">
            <input name="name" type="text" id="name" value="<?php get_data("name"); ?> name" size="50" /></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td colspan="2">&nbsp;</td>
          </tr>
          <tr>
            <td class="sidebar_box" ><label for="email">E-mail:</label> </td>
            <td class="sidebar_box" colspan="2"><input name="email" type="text" id="email" value="<?php get_data("email"); ?> email address" size="50" /></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td colspan="2">&nbsp;</td>
          </tr>
          
          <tr>
            <td>&nbsp;</td>
            <td colspan="2">&nbsp;</td>
          </tr>
          <tr>
            <td class="sidebar_box"><label for="location">Location*:</label></td>
            <td class="sidebar_box" colspan="2"><input name="location" type="text" id="location" value="<?php get_data("location"); ?> Location (optional)" size="50" /></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td colspan="2">&nbsp;</td>
          </tr>
          <tr>
            <td class="sidebar_box"><label for="comments">Message:</label></td>
            <td class="sidebar_box"colspan="2"><textarea name="comments" cols="45" rows="5" id="comments"><?php get_data("comments"); ?> Add your message in here.
            </textarea></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
          <tr>
            <td class="sidebar_box">* optional </td>
            <td class="sidebar_box" ><div align="center">
              <input type="submit" name="submit" id="submit" value="Send Message" />
            </div></td>
            <td class="sidebar_box">
              <div align="left">
                <input type="reset" name="Reset" value="Clear Form"  onclick="a_contact.php"/>
              </div></td>
          </tr>
        </table>


</form>
 

gaptrast

Member
Messages
123
Reaction score
0
Points
16
THANKS CYBRAX!! It worked!!

I have repped you++

I read something about how to send with attachment and I managed to do that. But I want user to upload their own pictures! I will try to figure it out. If i can not do it, i will post back:)
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Note that you can replace the use of output buffering (the ob_* functions) in the tutorial you linked to with heredoc strings:
PHP:
<?php
...
$message = <<<EOF
--PHP-mixed-$random_hash
Content-Type: multipart/alternative; boundary="PHP-alt-$random_hash" 

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

Hello World!!! 
This is simple text email message. 

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

<h2>Hello World!</h2> 
<p>This is something with <b>HTML</b> formatting.</p> 

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

--PHP-mixed-$random_hash
Content-Type: application/zip; name="attachment.zip"  
Content-Transfer-Encoding: base64  
Content-Disposition: attachment  

$attachment
--PHP-mixed-$random_hash--
EOF;
 

gaptrast

Member
Messages
123
Reaction score
0
Points
16
hmm
I did understand 50%

What is PHP-mixed and PHPalt ? Do I need to write them many times?
Why is it one version with text and one with HTML?
How can I get this into a mail form (like the code cybrax posted)`?
If I put this into cybrax' code, do I need to change (add php-mixed and stuff...) to the text/content and att. or only the attachment?

Hope you can help. ( I do not hestitate with repping:);))
 

cybrax

Community Advocate
Community Support
Messages
764
Reaction score
27
Points
0
The above code is intended mainly for a very simple web site contact form, it uses the local server mail() function to send the messages and is subject to certain limits, only so many emails can be sent an hour (have no idea what they are off the top my head but the topic has come up here before). The code could be made more elegant as 'misson' points out and has provided a link to site that you will probably end up bookmarking for future reference. There are a number of improvements that could (and probably should) be made to it before I post it in here again.

BTW - The plaintext option is so the message can still be read by those who have opted to block emails with html content.

This earlier post may be of some interest to you about using SMTP mailing, that is using somebody elses mail server rather than the X10 local one, in this case Google mail. Probably a good idea if you are planning to send large amounts of email as the daily limits are much higher.






Probably the best piece of advice anybody can give you is this:

1> Google is your friend, some problems are encountered time and time again by newcomers and so the answer is out there.
(even experienced site builders still google frantically to solve scripting related problems)
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
What is PHP-mixed and PHPalt ?
"--PHP-mixed-$random_hash" is the boundary delineating different parts of a multipart message (which is how you send attachments, as one part of a single multipart e-mail). "--PHP-alt-$random_hash" is the boundary for alternate versions of a particular part.

Do I need to write them many times?
Not many times, a specific number of times. You need each boundary at the start of a part, and at the end of a sequence of parts (with a "--" appended to the boundary).

How can I get this into a mail form (like the code cybrax posted)`?
If I put this into cybrax' code, do I need to change (add php-mixed and stuff...) to the text/content and att. or only the attachment?
As mentioned in my post:
Note that you can replace the use of output buffering (the ob_* functions) in the tutorial you linked to [emph. added] with heredoc strings:
the sample I posted was in response to the tutorial to which you linked, not in reference to Cybrax's code, though you could use heredoc syntax wherever you wished. As for their use over output buffering, heredocs are simpler (no need for additional function calls, just a simple assignment) and more readable (no need to switch to PHP simply to echo variables; instead, the value of the variables are interpolated directly into the string, though it looks like I left in one echo statement).

As for other questions you might have about multipart e-mail, start with the document referenced by the first two links and read what it links to.
 
Last edited:

gaptrast

Member
Messages
123
Reaction score
0
Points
16
hi,

thanks for reply.

I have searched a lot at google now and read alot, but there are still things I cant understand.

Normal emailing is working:)

I have added an upload script too, and its working:)

The only thing I need, is to get that file into the email as an attachment

my current code now is http://pastebin.com/tkgZrLFb

Thanks:cool:
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
I have searched a lot at google now and read alot, but there are still things I cant understand.
I wish it didn't, but study takes time. You'll get there eventually.

If you're having problems with multipart message concepts, consider how you'd solve the problem it solves.

The format of e-mails are defined by the Internet Message Format (IMF), which is a very simple format: a sequence of headers, followed by a blank line, followed by a body. Headers have a name and a value, separated by ": ". There are a few more details (such as line length limits and what characters to use for line termination), but that's the gist. Note that there is only a single body to contain content. What do you do if you want to send multiple things in a single message?

After you've thought about how you'd solve it, go back to multipart messages, which are part of the MIME standard. The idea behind them is rather simple: use special strings that don't appear in what's being sent as separators or terminators. They are similar in concept to the CSV format, but use longer separators. Also unlike CSV, each message can use a different separator, so the separator has to be recorded somewhere in the message, which is why the multipart content types have the "boundary" option.

Lastly, there are different reasons for sending multiple things in the same message. They may be different representations of the same thing, so only one of them needs to be used. These are multipart/alternative messages. They may be parts of a single whole, such as HTML and images that form a webpage, in which case you'd use the multipart/related type. They may be different types of things, such as an e-mail message, a word document and an image, for which you have multipart/mixed. MIME defines other multipart types.

A message may need to make use of different multipart types in the same message, so you can nest the types. This is accomplished by giving each part its own headers, which lets you define a Content-type header for a part. In the heredoc sample I posted above, there's a multipart/alternative nested in a multipart/mixed. If you grok XML, it might be structured as:
HTML:
<mixed>
  <alt>
    <text charset="iso-8859-1" encoding="7bit">
      Hello World!!!  
      This is simple text email message.
    </text>
    <html charset="iso-8859-1" encoding="7bit">
      <![CDATA[
      <h2>Hello World!</h2>  
      <p>This is something with <b>HTML</b> formatting.</p>  
      ]]>
    </html>
  </alt>
  <zip encoding="base64" disposition="attachment">...</zip>
</mixed>
 
Top