Home >Backend Development >PHP Tutorial >Sending Emails with PHP

Sending Emails with PHP

Christopher Nolan
Christopher NolanOriginal
2025-03-02 08:34:11829browse

Sending Emails with PHP

Core points

  • PHP provides an easy and efficient way to send emails, including basic plain text messages, HTML messages, and mail with attachments.
  • PHP's mail() function is used to send emails. For simple emails, it only requires three parameters: the address of the recipient, the subject, and the body of the email.
  • When sending HTML mail or mail with attachments, you need to use the MIME standard to break the mail into parts and separate them with selected boundaries. Each section should define what the content is, how it is encoded, how the content is handled, and the content itself.
  • Using the PHPMailer library can enhance the functionality of sending mail in PHP, which allows connecting to SMTP servers, adding attachments, handling errors, sending multiple mails, adding custom headers, and more.

You may want to write a script in PHP to send a friend an email with an interesting reply address…but there are more and more meaningful things to do! Of course, you may have other reasons: For example, you might need a cron job to notify you of the problem, or you will be notified when the user initiated script runs, or you have a Contact Us form to forward the message to you, or you want to demonstrate your PHP skills and write your own web-based mail client, or you need to set up a script that confirms via email—there are many other reasons to need to use PHP to send emails. And, it's very simple! In most cases, your PHP installation is able to send emails. If you are using a shared hosting, or have PHP installed using a package management system like apt-get, you're probably already set up. You need to worry about additional configuration only if you compile PHP from source or run PHP on Windows. In either case, there are a lot of resources available online to help you. Since this is beyond the scope of this article, I assume you have set it up. If not, Google will be your friend.

Super basic example

To send a very simple email, the code is as follows:

<?php mail($address, $subject, $message); ?>

Actually, that's all about sending a basic plain text email (if it doesn't work for you, check Google again for how to properly configure PHP). Now let's see how this looks in the script. For example, suppose you want the script to email you every time the query fails:

<?php
$query = "SELECT left_arm AS arm_in, right_leg AS leg_in, front_head AS head_in FROM hokey_pokey WHERE its_about = 'all'";
try {
    $result = $db->query($query);
    // ...
} catch (PDOException $e) {
    mail("bad_things@my_database.com", "Error in " . $_SERVER["SCRIPT_NAME"], $e->getMessage());
}
?>

If there are some unforeseen errors in your query execution, you will receive an email informing you which script has an error and what is the error.

Full HTML mail example

Now, let's see a complete multipart mail() example that contains an HTML body and a plain text alternative and a file attachment:

<?php mail($address, $subject, $message); ?>

For easier understanding of the basic concepts, some aspects of more typical email scripts have been simplified, although I will explain this in this section. First, the $emailList array is filled with some email addresses with which I want to share my email. The array is iterated at the end of the script and each address will receive a copy of my email. Next, the $headers string is built with various email headers. Each header in the string is separated by CRLF (rn) and complies with the RFC 2822 standard, which defines the format of email messages. "From: "Fluffy Mumsy" rn" From header specifies the email address from which the recipient will see the email from. “Reply-To: weregonnaberich@shhhsecret.comrn” The Reply-To header is the email address to which the email response should be sent. By making it different from the "From:" header, the possibility that this email is identified as spam increases (although if this is the only reason that causes the email client to mark this message as spam, then it may pass). "MIME-Version: 1.0rn" The MIME-Version header tells the server to expect Multi-purpose Internet Mail Extension in the body, which allows you to have more advanced emails than plain text. The "Content-Type: multipart/mixed; boundary="YaGottaKeepEmSeparated"rn" The "Content-Type" header actually does two things: it indicates that there will be multiple different types of parts in the body and specifies the string used to separate each part. This boundary string cannot appear anywhere else in the message, otherwise the mail client will not be able to parse the message correctly. For example, you could use "12" as the boundary, but it is likely to appear elsewhere in the mail. I selected "YaGottaKeepEmSeparated".Most people assign a randomly generated hash as a boundary, such as $boundary = md5(time()), because the chance of collision is very low. The content of novyrus.zip (here is located in the same directory as the script) is encoded by base64 and broken down into "blocks" so that the mail client can be easier to handle. The result is stored in $goodAttachment and will appear later. Finally, the composition of the email body... "--YaGottaKeepEmSeparatedrn" This is the first instance of using the boundary defined earlier and telling the mail client, "Hey, this is the beginning of the first part of the email message", which always starts with a double dash in front of the boundary string you selected. "Content-Type: multipart/alternative; boundary="EachEmailAlternative"rn" In addition to the "multipart/mixed" given in the email header, you can also use "multipart/alternative" in the body and different boundaries (specific to this breakdown) to provide an alternative format for messages. "-EachEmailAlternativen" This is the first instance of the nested boundary and launches the first alternative version of the message. "Content-Type: text/plain; charset="iso-8859-1"rn" This Content-Type header tells the mail client that this alternative is plain text. If the client cannot display more complex formats (such as HTML), it will use this version of the message. The "Content-Transfer-Encoding: 7bitrn" Content-Transfer-Encoding header specifies the encoding scheme used in the message. For historical reasons, "7bit" is the default value, so it can be omitted. I included it just to let you know. "You have cheap text email you have no money. Please ignore.rn" This is the message that people using non-HTML-functional readers will see in plain text versions. "-EachEmailAlternativen" The first alternative is finished and you can start the next alternative. "Content-Type: text/html; charset="iso-8859-1"rn" This Content-Type header notifies the client that this version is formatted as HTML, and the character set used. " ... rn" Note that the content of this version is very different from the plain text version, except that it contains HTML tags. Some spam filters might view this as another reason to prevent my mail from reaching my inbox. "--YaGottaKeepEmSeparatedrn" This is the multipart/mixed boundary, indicating that you have reached the end of the message body section that contains all alternatives. "Content-Type: application/zip; name="novyrus.zip"rn" The Content-Type header indicates that the next part of the email is an attachment (novyrus.zip file), and it is a ZIP file. "Content-Transfer-Encoding: base64rn" 7-bit encoding limits characters to seven bits and may not faithfully represent all binary characters required by a ZIP file, which is why the file is base64 encoded and chunked. The Content-Transfer-Encoding header here lets the client know how to decode the attachment file. The "Content-Disposition: attachmentrn" Content-Disposition header details how the content is rendered; there are two possible values: attachment and inline.While it makes little sense to display a ZIP file as an inline element in a message, it is very useful for embedding images. $goodAttachment . "rn" The contents of the attached file are simply dumped into the mix. "--YaGottaKeepEmSeparated--" This is the final boundary, the declaration ends by adding a set of double dashes to the end without any content.

Summary

That's it! You've learned how to send ultra-basic text emails and full HTML emails with attachments. A simple email simply calls the mail() function. For HTML messages, you need to break down the email into sections using the MIME standard and separate it with the boundary of your choice. You then define what the content is, how it is encoded, how the content is handled, and the content itself. Depending on who you plan to send emails, you need to be aware of what might make your email more likely to be marked as spam, just in case you really want to send something serious. Pictures from Photosani / Shutterstock

FAQs about sending emails with PHP

(The FAQ part is omitted here because the length is too long and does not match the pseudo-original goal. The content of the FAQ part is consistent with the original text. Just make simple statement adjustments to the original text to complete pseudo-original.)

The above is the detailed content of Sending Emails with PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn