Use MySQL to extract automated emails

Sending emails with PHP

February 10, 2020
  1. Home
  2. »
  3. PHP tutorial
  4. »
  5. Sending emails with PHP

The email function of PHP is very practical because we can use it to send form data or create entire newsletter scripts. You can also use this method for a guest book, e.g. that you receive an email when someone enters the guest book.

Important
If you run this function on your computer, you will usually get an error message:
Warning: mail (): ...

This is because your local server no Can send emails. You can ignore the error message, because it shouldn't appear on the real server anymore.

With the PHP function mail() you can send the mails, the command looks like this:

It makes sense to save the individual texts in variables so that you can keep an overview.

Only text e-mails can be sent, HTML e-mails are a bit more complicated (see below).

A finished PHP mail function would look like this:

$ subject = "The mail function";
$ text = "Here you learn how to send mail with PHP";
mail ($ recipient, $ subject, $ text, $ from);

This is how a mail from [email protected] at [email protected] sent.

If your server is set up correctly, the email should arrive immediately.

Of course, you can also request the texts from a form.

The mail is sent as it is in the source text of the script. For example, if you have a ü by & uuml; (HTML code for a ü), so it will be written later in the mail: & uuml;. Because the umlauts are not displayed there, but the HTML code for them (for text emails).

In addition, you are not allowed to use HTML commands, e.g. if it says in the e-mail, this is not converted into a line break, but instead it is written in the mail.

For line breaks, a simple Enter in the source text or is sufficient \ n. To indent a bit, you have to use tab or space.

HTML emails

You can also send HTML emails with PHP. But you should know that not all email programs and email providers display these HTML emails correctly. Also, not all e-mail programs and providers display all HTML commands; many providers only allow certain commands to protect their visitors from malicious e-mails.

In order for PHP to be able to send HTML emails, you have to use the $ from Change variable something.

$ subject = "The mail function";
$ from. = "Content-Type: text / html \ r \ n";
$ text = "Here you can learn how to use PHP to send emails
mail ($ recipient, $ subject, $ text, $ from);

The variable $ from is simply added, but make sure that after the sender there is an \ r \ n must stand.

We have also given a reply address.

With the text we have to be careful that we have to mask the quotation marks "with a backslash (\).

Example 2:

$ text = "Here you learn how to send mails with PHP ";

In this case, the text of the message must be formatted using HTML! Enter is no longer sufficient for a line break, you have to use
.

Author: Nils Reimers