10. E-Mails

Sending a plain text email

If you are running PHP in a place that has a configured SMTP server, you can send emails using mail(). Practically all hostings are already prepared.

mail(string $email_destinatario, string $asunto, string $mensaje, array $headers[]);

In the example we indicate, through headers, the sender's address (us, through From) and configure the email to accept accents or special Spanish characters (Content-type).

$headers = [
    'From' => 'curso@php.com',
    'Content-type' => 'text/plain; charset=utf-8'
];
mail('correo@falso.com', 'Special day', 'Thanks for subscribing', $headers);

Line breaks are done with "\n".

Configuring the SMTP server

In case you are working locally or on a VPS, your emails will not be sent. You need to either install an SMTP server or configure PHP to use an external one. One option is to use an SMTP client that connects to a provider, moving the functionality outside. With ssmtp we can achieve this easily.

First we install it.

sudo apt-get install ssmtp

We open the PHP configuration, php.ini.

sudo nano /etc/php/{versión}/cli/php.ini

Modifying the following line.

sendmail_path = /usr/sbin/ssmtp -t

We save. Now we will configure ssmtp to connect with, for example, Gmail.

sudo nano /etc/ssmtp/ssmtp.conf

Inside we would add the necessary account data.

root=micuenta@gmail.com
mailhub=smtp.gmail.com:587
rewriteDomain=midomonio.com
hostname=FQDN.yourdomain.com
UseTLS=Yes
UseSTARTTLS=Yes
AuthUser=micuenta@gmail.com
AuthPass=micontraseña
FromLineOverride=yes

Sending an email in HTML

The procedure does not vary much, we just have to indicate in the Content-type header that it accepts HTML and add MIME-Version.

// Our message must be HTML
$mensaje = '
<html>
<head>
  <title>Happy SPAM day</title>
</head>
<body>
  <p>How are you?</p>
  <table>
    <tr>
      <th>User</th>
      <th>Surname</th>
      <th>Birth</th>
    </tr>
    <tr>
        <td>Barba</td>
        <td>Negra</td>
        <td>1718</td>
    </tr>
  </table>
</body>
</html>
';

// Define what type our message will be: HTML. And the sender's address.
$headers = [
    'MIME-Version' => '1.0',
    'Content-type' => 'text/html; charset=utf-8',
    'From' => 'curso@php.com'
];

// We send it
mail('correo@falso.com', 'Special day', $mensaje, $headers);

Using the PHPMailer plugin

If we need to perform advanced actions, such as indicating the SMTP server configuration or sending attachments, we can make use of PHPMailer. You will have to install it in your project with Composer.

composer require phpmailer/phpmailer

Here you can see a simple example.

<?php
// Import
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once('vendor/autoload.php');

// Create object
$mail = new PHPMailer();

try {
    // SMTP server configuration
    $mail->isSMTP();
    $mail->Host       = 'smtp.correo.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'usuario@correo.com';
    $mail->Password   = 'contraseña';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    $mail->setFrom('emisor@correo.es', 'Sender name');
    // Who receives it
    $mail->addAddress('receptor@correo.es', 'Recipient name');

    // Content
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body    = 'HTML of my message';

    // Send
    $mail->send();

} catch (Exception $e) {
    // Errors
    echo $e;
}
Activity 1

1. Show a banner warning that the user must accept the Cookies policy with a button.

2. When it is clicked, create a cookie.

3. Do not show the banner again while it exists.

Activity 2

The visitor must have the possibility to change the language of the page.

  • Create a button to update the language.
  • Save the selection in a cookie.
  • Show the appropriate text depending on the existing cookie. If you want, in the middle of the page.

ES - Bienvenido

EN - Welcome

IT - Benvenuto

FR - Bienvenue

Pro:

  • Also save the background color.
  • Use flags.

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.