Sunday, June 1, 2014

PHP Tutorials -> Mail

PHP Mail

The mail() Function

The mail() function is used to send emails.
Syntax
mail(to,subject,message,headers,parameters)

Parameter
Description
to
Required. Specifies the receiver / receivers of the email
subject
Required. Specifies the subject of the email. Note: This parameter cannot contain any newline characters
message
Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters
headers
Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)
parameters
Optional. Specifies an additional parameter to the sendmail program (the one defined in the sendmail_path configuration setting). (i.e. this can be used to set the envelope sender address when using sendmail with the -f sendmail option)

PHP Simple Text E-Mail

The simplest way to send an email with PHP is to send a simple text email.
This is a simple text email where we define the variables and send a mail:
<?php
$to = "someone@someplace.com";
$subject = "Test mail";
$message = "Hello! This is a simple text email message.";
$from = "someonelse@anotherplace.com";
$headers = "From: $from";
 
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>



PHP Mail Form

Using PHP you can create a feedback form for your website. In this example it sends a text message to a specified e-mail. 
When using HTML forms with PHP, any form element in the HTML form will automatically be available to the PHP script.
This is how this example works:
  • Check if the email input is set
  • If it is not set (like when the page is first visited) it will output the HTML mail form
  • If the email input is set (like after the form is filled out) it will send the mail from the form
  • When submit is pressed after the form is filled out, the page reloads, sees that the email input is set, and sends the mail.

<html>
<body>
<?php
if (isset($_REQUEST['email']))
  {
  $email = $_REQUEST['email'] ; 
  $subject = $_REQUEST['subject'] ;
  $message = $_REQUEST['message'] ;
  mail( "someone@someplace.com", "Subject: $subject",
  $message, "From: $email" );
 
  echo "Thank you for using our mail form";
  }
else
  {
  echo "<form method='post' action='mailform.php'>
  Email: <input name='email' type='text' /><br />
  Subject: <input name='subject' type='text' /><br />
  Message:<br />
  <textarea name='message' rows='15' cols='40'>
  </textarea><br />
  <input type='submit' />
  </form>";
  }
?>
</body>
</html>

0 comments:

Post a Comment