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" $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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech
