Is This the Correct Way to Send Email with PHP

Which is the best way to send email using PHP

I strongly recommend using some mature PHP class, which solves many problems you would encounter. Such example of a quality PHP mailer library could be PHPMailer

How can I send an email using PHP?

It's possible using PHP's mail() function. Remember the mail function will not work on a local server.

<?php
$to = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

Reference:

  • mail

Is this the correct way to send email with PHP?

While that should work, I would strongly recommend using a prebuilt Mail/SMTP class such as Zend_Mail. While I don't think the whole Zend Framework is the cat's pajamas, I do have a very good opinion of their mail handling code.

EDIT: I should also add that using a prebuilt Mail/SMTP class will abstract almost all of the complexity/structure of multi-part emails.

Update 2009-05-06: Answering your question directly.

  • Are the UTF-8 declarations and attachments well formed?

They look decent enough.

  • Do I need to use quoted_printable_decode()? If yes, where?

No. You would want to use quoted_printable_decode() only if you are decoding an email message. Not when you are encoding one. Should you use quoted_printable_encode()? I will discuss this next.

  • Content-Transfer-Encoding: 7 or 8 bits? I've always seen 7 but since I'm sending a UTF-8 encoded mail I'm not sure.

Only use 8bit encoding if you know that the destination SMTP server can support it. However, since you are passing your email off to the local MTA, I wouldn't recommend setting this value. The default value is 7bit encoding, but it has it's own set of restrictions: up to 998 octets per line of the code range 1-127 with CR and LF only allowed to appear as part of the CRLF line ending (https://www.rfc-editor.org/rfc/rfc2045#section-2.7).

I would recommend you use the Quoted-Printable (https://www.rfc-editor.org/rfc/rfc2045#section-6.7) Content-Transfer-Encoding. Where you are calling trim(strip_tags($message, '<a>')) and trim($message) you will want to enclose those with quoted_printable_encode(trim(...)).

  • Should I use mb_send_mail() or mail() is enough?

If you know you are not going to be handling Multibyte messages (Japanese, Korean, Chinese, etc.) then mail() should suffice.

Now that I've answered your initial questions, let me tell you where some problems exist.

  1. You are specifying that the Character set of your Plain Text and Html content parts are UTF-8, however it doesn't appear as you are actually ensuring that they really are UTF-8 encoded.
  2. You are checking for null in $to, $bcc, $attachments before you further process them, however, you aren't doing anything when they may actually be null. So, if you happen to receive a null for $to, you don't process the variable, but you continue to send an email to null.

As of right now, that's all I am going to go into but I am still going to highly recommend a pre-built solution as they have had lots of users/time to work out bugs.

Send mail reliably with PHP?

From my experience, PHPMailer is the way to go - https://github.com/PHPMailer/PHPMailer

You need to get access to a SMTP server you will use to send your mail. This could either be the Google SMTP server (a @gmail.com email address) or your company's email server.

A quick example to do this using Google SMTP server is:

1) Install PHPMailer using composer from a terminal / shell:

composer require phpmailer/phpmailer

2) Include the composer generated autoload file and PHPMailer in your php script:

// Load Composer's autoloader
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

3) Send email using:

$mail = new PHPMailer(true);
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'YOUREMAIL@gmail.com'; // SMTP username
$mail->Password = 'YOUREMAILPASSWORD'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
$mail->Port = 587; // TCP port to connect to

//Recipients
$mail->setFrom('YOUREMAIL@gmail.com', 'Mailer');
$mail->addAddress('TOADDRESS'); // Add a recipient

// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';

$mail->send();

Read the PHPMailer documentation at: https://github.com/PHPMailer/PHPMailer

Send email with PHP from html form on submit with the same script

EDIT (#1)

If I understand correctly, you wish to have everything in one page and execute it from the same page.

You can use the following code to send mail from a single page, for example index.php or contact.php

The only difference between this one and my original answer is the <form action="" method="post"> where the action has been left blank.

It is better to use header('Location: thank_you.php'); instead of echo in the PHP handler to redirect the user to another page afterwards.

Copy the entire code below into one file.

<?php 
if(isset($_POST['submit'])){
$to = "email@example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

Original answer


I wasn't quite sure as to what the question was, but am under the impression that a copy of the message is to be sent to the person who filled in the form.

Here is a tested/working copy of an HTML form and PHP handler. This uses the PHP mail() function.

The PHP handler will also send a copy of the message to the person who filled in the form.

You can use two forward slashes // in front of a line of code if you're not going to use it.

For example: // $subject2 = "Copy of your form submission"; will not execute.

HTML FORM:

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

PHP handler (mail_handler.php)

(Uses info from HTML form and sends the Email)

<?php 
if(isset($_POST['submit'])){
$to = "email@example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
// You cannot use header and echo together. It's one or the other.
}
?>

To send as HTML:

If you wish to send mail as HTML and for both instances, then you will need to create two separate sets of HTML headers with different variable names.

Read the manual on mail() to learn how to send emails as HTML:

  • http://php.net/manual/en/function.mail.php

Footnotes:

  • In regards to HTML5

You have to specify the URL of the service that will handle the submitted data, using the action attribute.

As outlined at https://www.w3.org/TR/html5/forms.html under 4.10.1.3 Configuring a form to communicate with a server. For complete information, consult the page.

Therefore, action="" will not work in HTML5.

The proper syntax would be:

  • action="handler.xxx" or
  • action="http://www.example.com/handler.xxx".

Note that xxx will be the extension of the type of file used to handle the process. This could be a .php, .cgi, .pl, .jsp file extension etc.


Consult the following Q&A on Stack if sending mail fails:

  • PHP mail form doesn't complete sending e-mail

Best way of sending an email from the result of a PHP script

Going by exactly what you asked, you can use output buffering:

<?php
//start buffering output (Everything that was supposed to go to the browser is instead stored)
ob_start();
?>
<html>
<!-- write lots of HTML, including some data from db -->
<div><?php echo $data; ?></div>
</html>
<?php
//get the data that was buffered
$big_html_message = ob_get_clean();

mail($to, $subject, $big_html_message);

Send HTML in email via PHP

It is pretty simple. Leave the images on the server and send the PHP + CSS to them...

$to = 'bob@example.com';

$subject = 'Website Change Request';

$headers = "From: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "Reply-To: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "CC: susan@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

$message = '<p><strong>This is strong text</strong> while this is not.</p>';

mail($to, $subject, $message, $headers);

It is this line that tells the mailer and the recipient that the email contains (hopefully) well-formed HTML that it will need to interpret:

$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

Here is the link I got the information from... (link)

You will need security though...



Related Topics



Leave a reply



Submit