Being designed to create, deploy, and run applications in lightweight and portable containers, it makes sense that you can’t send emails directly from Docker.
But, you can use Docker to run an application that can process data and send emails.
In this ‘Docker send email’ guide, I’ll show you how you can set up your Docker environment with PHP and Mailtrap, and send emails within a Dockerized application.
Let’s get to it!
Sending emails using Docker and PHP through SMTP
Step 1. Configure Mailtrap SMTP
As Docker doesn’t have a built-in SMTP, you first need to choose an email service provider to send emails. I chose Mailtrap because it offers both SMTP and email API, and on top of that, it allows me to test my emails before I send them.
To configure Mailtrap SMTP, simply go to the signup page and register for a free account.
Then, navigate to the Sending Domains → SMTP/API Settings tab in your inbox, where you can find the details for host, port, username, and password, which you’ll use in the next section of the tutorial.
Step 2. Configure PHPMailer
As well as a service provider, you will also need PHPMailer to send emails via PHP from Docker with SMTP.
PHPMailer is an email-sending library for PHP that provides the user with powerful functionality to send emails from SMTP over a TCP connection, create HTML emails with attachments, send them to multiple recipients, and more.
It’s also super secure, supporting MIME encryption and the use of TLS and SSL.
You can install PHPMailer either via Composer (recommended by PHPMailer’s creators) or manually.
If you opt for Composer, simply add this line to your composer.json file:
"phpmailer/phpmailer": "~6.9"
or run:
composer require phpmailer/phpmailer
If you decide to install PHPMailer manually, you need to:
- Download files with PHPMailer source code from the official PHPMailer GitHub repository
- You can also check out the official documentation for a more detailed installation instruction
- Copy the contents of the PHPMailer folder to one of the include_path directories specified in your PHP configuration
- Load each class file manually
On top of this, you should also add an Exception class, which will help you handle and debug errors. By doing this, you will see a message saying Exception class is not found if there is an error.
To add Exception class, use the following code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
The path in the require
statements should be the actual path where you’ve placed the PHPMailer library files in your project.
If your PHP installation doesn’t have OpenSSL enabled by default you plan to use TLS or SSL for email transmission, you need to edit your php.ini configuration file. Here’s how to do it:
- Locate your php.ini file
- Open your php.ini file with administrative privileges and search for
;extension=openssl
- Remove the semicolon so the line reads
extension=openssl
and save your file - Restart your web server
To ensure you’ve enabled the OpenSSL extension, simply:
- Create a PHP file and in it write
<?php phpinfo(); ?>
- Access it via your web browser
- Look for the OpenSSL section in the output (if it’s without any warnings, you’ve successfully enabled the OpenSSL extension)
Additionally, you should consider placing your custom scripts and libraries in the usr/local directory within your Docker container. This directory, as its name suggests, is often used for user-installed software and data.
Step 3. Create a Dockerfile
Now, open either your favorite text or code editor (I personally use Visual Studio Code) and paste the following code into it:
FROM php:8.2-fpm
# Update the package list
RUN apt-get update && \
# Install only necessary libraries
apt-get install -y zlib1g-dev libzip-dev && \
# Install PDO MySQL for database connectivity
docker-php-ext-install pdo_mysql && \
# Clean up to reduce image size
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# Set the working directory inside the container
WORKDIR /var/www/html
# Copy the application source code
COPY . .
# Expose port 9000 for the PHP-FPM server
EXPOSE 9000
# Start the PHP-FPM server
CMD ["php-fpm"]
Once you copy the code, it’s important to save the file as Dockerfile with no file extension to make Docker recognize it. You should also save the file in the root of the project directory where you intend to build your Docker image.
Notes:
- Since PHPMailer can communicate directly with an SMTP, I didn’t add an MTA such as sendmail or its configuration
- Ensure that composer.json and composer.lock files are in the same directory as the Dockerfile when building the image. If they don’t, the build will likely fail.
- Make sure that your application is configured to communicate with the PHP-FPM on the default port 9000
Step 4. Write PHP code
After creating a Docker file, we need to write a PHP script for sending plain text emails.
But first, we need to make sure PHPMailer is included in your project.
If you used Composer for installation, include the Composer-generated autoload.php file, like so:
require 'path/to/composer/vendor/autoload.php';
In case you installed PHPManually, initialize it like this:
// Adjust the path according to where you've placed the PHPMailer library in your project
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';
require 'path/to/PHPMailer/src/Exception.php';
Then, use the script I prepared for you and paste it into your project script accessible within your Docker container and then later change it according to your liking:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Adjust the path according to where your autoload.php is located
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// SMTP config
$mail->isSMTP();
$mail->Host = getenv('SMTP_HOST');
$mail->SMTPAuth = true;
$mail->Username = getenv('SMTP_USER'); $mail->Password = getenv('SMTP_PASS'); $mail->SMTPSecure = 'tls';
$mail->Port = getenv('SMTP_PORT');
// Sender and recipient settings
$mail->setFrom('info@mailtrap.io', 'Mailtrap');
$mail->addReplyTo('info@mailtrap.io', 'Mailtrap');
$mail->addAddress('recipient1@mailtrap.io', 'Tim'); // Replace with recipient's email and name
// Setting the email content
$mail->isHTML(false); // Set email format to plain text
$mail->Subject = 'Test Email via Mailtrap SMTP using PHPMailer';
$mail->Body = "This is a test email I'm sending using SMTP mail server with PHPMailer in plain text.";
if ($mail->send()) {
echo 'Message has been sent';
} else {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
You can also secure your email content and improve your authentication process by ensuring that your SMTP email server supports SSL/TLS with the following commands:
$mail->SMTPSecure = 'tls'; // Or 'ssl'
$mail->Port = 587; // Or 465 for SSL
Step 5. Create a Bash script
Now, let’s include bash
, which can come in handy if you want to keep sensitive information like SMTP credentials out of your Dockerfile or PHP code.
Here’s an example of how I used a bash
script named setup_env.sh to set up environment variables for my Docker container:
#!/bin/bash
# Export environment variables
export SMTP_HOST='live.smtp.mailtrap.io'
export SMTP_USER='1a2b3c4d5e6f7g'
export SMTP_PASS='1a2b3c4d5e6f7g'
export SMTP_PORT=2525
We also have to make the script executable with the following command:
chmod +x setup_env.sh
Step 6. Add Docker Compose
Create a docker-compose.yml file in the root of your project, which will define all the services needed for your application.
It should look something like this:
version: '3.8'
services:
php-mailer:
build: .
image: php-mailer-app
volumes:
- .:/app
environment:
SMTP_HOST: ${SMTP_HOST}
SMTP_USER: ${SMTP_USER}
SMTP_PASS: ${SMTP_PASS}
SMTP_PORT: ${SMTP_PORT}
Notes:
- The SMTP variables (SMTP_HOST, USER, and PASS) you use in your PHP code must match with these defined in docker-compose.yml
- Remember that path formats and file permissions are different between Linux, Microsoft Windows, and MacOS, so make sure to adjust these settings accordingly when you’re configuring mapping either in the .yml file or previously created Dockerfile
Step 7. Start the container
Now, before launching the Docker container, we need to execute the bash script to ensure that the environment variables are properly set. To do this, simply run the following command in the same shell session:
source ./setup_env.sh
Next, you can run the following command in the same directory as your docker-compose.yml to build an image for your application and start the container:
docker-compose up --build
- The
--build
makes sure Docker Compose rebuilds the image, incorporating any changes
To stop or remove containers, networks, and volumes created by Docker Compose, you can use:
docker-compose down
Step 8. Enter Docker container and run PHP script
After starting the Docker container, you may need to execute PHP scripts which will send the email. To do this, you can use the docker exec
command to enter the running container and run PHP script.
Here’s how you can do it:
- Enter the Docker container: Use the following command to enter the running Docker container:
docker-compose exec php-mailer bash
- Run PHP script: Once inside the container, navigate to the directory containing your PHP script and execute it using the PHP interpreter. For example:
php send_email.php
Replace send_email.php
with the name of your PHP script.
- Test configuration: While inside the container, you can test the configuration, troubleshoot issues, or perform any other necessary tasks related to your PHP application.
- Exit container: After you’ve finished your tasks, you can exit the container by typing:
exit
This will return you to your host machine’s shell.
By using docker exec
, you can directly interact with the running container, allowing you to execute PHP scripts and perform various operations within the Docker environment.
Sending HTML email
To send an HTML email, you can use the PHP script that uses PHPMailer I slightly modified. More specifically, I just set the email content to indicate that the body is HTML, instead of plain text.
Check it out:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// SMTP configuration
$mail->isSMTP();
$mail->Host = getenv('SMTP_HOST');
$mail->SMTPAuth = true;
$mail->Username = getenv('SMTP_USER');
$mail->Password = getenv('SMTP_PASS');
$mail->SMTPSecure = 'tls';
$mail->Port = getenv('SMTP_PORT');
// Sender and recipient settings
$mail->setFrom('info@mailtrap.io', 'Mailtrap');
$mail->addReplyTo('info@mailtrap.io', 'Mailtrap');
$mail->addAddress('recipient1@mailtrap.io', 'Recipient Name'); // Replace with recipient's email and name
// Setting the email content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Your HTML Email Subject Here';
$mail->Body = '<h1>This is the HTML message body</h1><p>This is a test email I\'m sending using SMTP mail server with PHPMailer in HTML format.</p>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if ($mail->send()) {
echo 'Message has been sent';
} else {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
Notes:
- I used
$mail->isHTML(true);
to indicate that the email body will be HTML - Define
$mail->Body
with your HTML content and include tags such as<h1>
or<p>
- For email clients that do not support HTML, you can provide an alternative text version of the email in
$mail->AltBody
Send email with attachments
For emails with attachments, just include the addAttachment()
method of PHPMailer, which allows us to send files, in our PHP script.
Here’s a code example:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// SMTP configuration
$mail->isSMTP();
$mail->Host = getenv('SMTP_HOST');
$mail->SMTPAuth = true;
$mail->Username = getenv('SMTP_USER');
$mail->Password = getenv('SMTP_PASS');
$mail->SMTPSecure = 'tls';
$mail->Port = getenv('SMTP_PORT');
// Sender and recipient settings
$mail->setFrom('info@mailtrap.io', 'Mailtrap');
$mail->addReplyTo('info@mailtrap.io', 'Mailtrap');
$mail->addAddress('recipient1@mailtrap.io', 'Recipient Name'); // Replace with recipient's email and name
// Setting the email content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Your Email Subject Here With Attachment';
$mail->Body = '<h1>This is the HTML Message Body</h1><p>This is a test email I\'m sending using SMTP mail server with PHPMailer in HTML format with attachment.</p>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
// Attachments
$mail->addAttachment('/path/to/file1.pdf'); // Add attachments
$mail->addAttachment('/path/to/file2.jpg', 'new.jpg'); // Optional name
if ($mail->send()) {
echo 'Message has been sent with attachment';
} else {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
- To attach a file, use
$mail->addAttachment('/path/to/file');
- Note that the first parameter is the path to the file you want to attach, and it should be accessible within your Docker container
- You can call
addAttachment()
multiple times if you want to attach more than one file - For error handling, you can use
try…catch
as it allows you to catch exceptions thrown by PHPMailer
Send email to multiple recipients
To send emails to multiple recipients, we have to modify the PHP script again, this time by simply adding addAddress()
, addCC()
, or addBCC()
for each recipient.
Here’s how you can do it:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// SMTP configuration
$mail->isSMTP();
$mail->Host = getenv('SMTP_HOST');
$mail->SMTPAuth = true;
$mail->Username = getenv('SMTP_USER');
$mail->Password = getenv('SMTP_PASS');
$mail->SMTPSecure = 'tls';
$mail->Port = getenv('SMTP_PORT');
// Sender and recipient settings
$mail->setFrom('info@mailtrap.io', 'Mailtrap');
$mail->addReplyTo('info@mailtrap.io', 'Mailtrap');
// Adding multiple recipients
$mail->addAddress('recipient1@mailtrap.io', 'Recipient1 Name');
$mail->addAddress('recipient2@mailtrap.io', 'Recipient2 Name'); // Repeat for each recipient
// Adding CC and BCC recipients
$mail->addCC('ccrecipient@mailtrap.io', 'CC Recipient Name');
$mail->addBCC('bccrecipient@mailtrap.io', 'BCC Recipient Name');
// Setting the email content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Email to Multiple Recipients';
$mail->Body = '<h1>HTML Message Body</h1><p>This is a test email sent to multiple recipients using SMTP with PHPMailer.</p>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if ($mail->send()) {
echo 'Message has been sent to multiple recipients';
} else {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
And here’s an explanation of each of the methods we used:
<strong>addAddress()</strong>
– Used for each recipient you want to send the email directly to.<strong>addCC()</strong>
– Used to add recipients who will receive a carbon copy of the email and make them visible to other recipients.addBCC()
– Used to add recipients who will receive a blind carbon copy of the email, making them invisible to other recipients of the message.
Sending emails using Docker through email API
Now it’s time to say goodbye to our friend PHPMailer because when you use an API for email sending, your method of sending email shifts from SMTP to HTTP requests.
Let me show you how it works.
Step 1. Configure Mailtrap API
If you plan to use the API to send emails, you can use the official Mailtrap PHP package to seamlessly add the email-sending functionality to your app.
You can find your API token in the SMTP/API Settings where you can also choose the desired code sample, which, in this case, is PHP.
Step 2. Create a Dockerfile
Like with sending with SMTP, we need to create a Dockerfile first. Here’s what I used:
FROM php:8.2-cli
# Ensure cURL is available for PHP to use
RUN apt-get update && apt-get install -y curl libcurl4-openssl-dev
WORKDIR /app
# Copy your PHP script into the container
COPY . /app
This particular Dockerfile uses the php:8.2-cli image as a base, installs cURL, and sets up a working directory /app inside your container. Then, it copies the contents of your currency directory (where your PHP script is) into the /app directory of the container.
Step 3. Write PHP code with Mailtrap API
Now, we need a PHP script as it’s responsible for sending the email through Mailtrap’s email API. It will use cURL
to make a POST request to Mailtrap’s API endpoint.
Just make sure it’s in the same directory as your Dockerfile, or at least in a subdirectory that is copied into the Docker image, and insert the following code in it:
<?php
$apiToken = getenv('API_TOKEN'); // Assuming you've set this environment variable
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://send.api.mailtrap.io/api/send',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode([
// Your API payload here
]),
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $apiToken",
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
// Check for errors and handle the response
if ($response === false) {
// curl_exec() failed
$error_msg = curl_error($curl);
echo "cURL Error: $error_msg";
} else {
// Success, handle $response
echo "Response: $response";
}
curl_close($curl);
Step 4. Create a Bash script
A Bash script for API configuration allows you to configure your environment variables related to Mailtrap email API. It can set the API token and any other necessary configuration without hardcoding them into your application’s code or Dockerfile.
Here’s what you can use:
#!/bin/bash
# Export environment variables for Mailtrap API
export API_TOKEN='yourMailtrapApiToken'
# any other environment variables...
# Note: You can then source this script before running your Docker container
# to make these variables available to your application.
Notes:
- To make these variables available to your application, you’ll have to source them before running your Docker container, which I’ll go over in Step #5
- Don’t forget to replace
yourMailtrapApiToken
with your actual Mailtrap API token
Step 5. Add a Docker Compose
Similarly to what we did with SMTP sending, we need to create a docker-compose.yml file in the root directory of the project that specifies how to build and run the containerized PHP application.
Here’s an example of a configuration:
version: '3.8'
services:
php-mailer:
build: .
image: php-mailer-app
volumes:
- .:/app
environment:
- API_TOKEN=${API_TOKEN}
hostname: custom-mailer-hostname
Don’t forget to replace API_TOKEN=yourMailtrapApiToken with the actual Mailtrap API token for the script to authenticate with the Mailtrap API.
Step 6. Start the container
Remember the Bash script? Now, we need to source it before running the Docker container. For this, you can use the following command in the same shell session:
source ./setup_env.sh
Lastly, to build an image for your application and to start the container, run the following command in the same directory as your docker-compose.yml:
docker-compose up --build -d
- The
--build
makes sure Docker Compose rebuilds the image, incorporating any changes
Similarly to what you would do with SMTP, you can use this command to stop or remove containers, networks, and volumes created by Docker Compose:
docker-compose down
Notes:
- Ensure that
API_TOKEN=yourMailtrapApiToken
is correctly replaced with your actual Mailtrap API token in the docker-compose.yml file. - Similar to sending emails with SMTP, you can interact with the container directly using command:
docker-compose run php-mailer bash
Sending HTML email
To send an HTML email, we simply need to format the html
field in our CURLOPT_POSTFIELDS
array with the desired HTML in the PHP script.
This field represents the body of the email, and by inserting HTML content here, we essentially instruct the Mailtrap email API to treat the email body as HTML.
Here’s what I used:
<?php
// Retrieve the API token from the environment variable
$apiToken = getenv('API_TOKEN');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://send.api.mailtrap.io/api/send',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode([
'from' => [
'email' => 'mailtrap@mailtrap.club',
'name' => 'Mailtrap Test'
],
'to' => [
[
'email' => 'recipient@example.com', // Replace with the recipient's email
]
],
'subject' => 'You are awesome!',
'html' => '<h1>Congratulations!</h1><p>You have successfully sent an HTML email using Mailtrap\'s email API.</p>',
// Providing a plain text version for email clients that do not support HTML
'text' => 'Congratulations! You have successfully sent an HTML email using Mailtrap\'s email API.'
]),
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $apiToken", // Use the API token here
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Note that the text
field is optional, but I recommend keeping it as it provides a plain text alternative, which can come in handy for email clients that do not support HTML.
Send email with attachments
Paste the following code into your PHP script to send email with attachments in Docker with email API:
<?php
$apiToken = getenv('API_TOKEN'); // Assuming you've set this environment variable
$curl = curl_init();
// Example of encoding attachments
$pdfAttachment = base64_encode(file_get_contents('/path/to/document.pdf'));
$imageAttachment = base64_encode(file_get_contents('/path/to/image.jpg'));
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://send.api.mailtrap.io/api/send',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode([
// Other email fields...
'attachments' => [
[
'content' => $pdfAttachment,
'filename' => 'document.pdf',
'type' => 'application/pdf', // Correct MIME type for a PDF file
'disposition' => 'attachment',
],
[
'content' => $imageAttachment,
'filename' => 'image.jpg',
'type' => 'image/jpeg', // Correct MIME type for a JPEG image
'disposition' => 'attachment',
]
]
]),
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $apiToken",
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
// Error handling as shown above
curl_close($curl);
Of course, don’t forget to replace the placeholder https://api.emailservice.com/send
with actual Mailtrap endpoints.
Send email to multiple recipients
Similarly, to send email to multiple recipients from Docker with email API, use the following code snippet:
<?php
require 'vendor/autoload.php';
$apiToken = getenv('API_TOKEN');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://send.api.mailtrap.io/api/send',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([
'from' => [
'email' => 'sender@example.com',
'name' => 'Sender Name'
],
'to' => [
[
'email' => 'recipient1@example.com',
'name' => 'Recipient One'
],
[
'email' => 'recipient2@example.com',
'name' => 'Recipient Two'
]
// Add more recipients as needed
],
'cc' => [
[
'email' => 'cc1@example.com',
'name' => 'CC Recipient One'
],
// Add more CC recipients as needed
],
'bcc' => [
[
'email' => 'bcc1@example.com',
'name' => 'BCC Recipient One'
],
// Add more BCC recipients as needed
],
'subject' => 'Your Subject Here',
'html' => '<h1>Your HTML Content Here</h1>',
// Attachments and other fields as needed...
]),
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $apiToken",
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Potential issues and troubleshooting in Docker
- Variables not being recognized – If your application isn’t using the environment variables you’ve set, you need to make sure you’ve correctly sourced the Bash script by running
source ./setup_env.sh
.- Additionally, you can check whether the environment variable names in the Bash script match the expected ones in your PHP code and yml.file
- Docker daemon not running – If you encounter a message that Docker daemon is not running when you try to start your Docker container, you need to start the Docker service on your system by running
sudo systemctl start docker
if you’re on Linux, or simply starting the application if you’re on Windows or macOS. - Unauthorized or invalid API token – If you’re having Docker authentication or connection issues with the Mailtrap email API, you can double-check whether you correctly set your API token in the Bash script and whether you sourced it correctly. You can also log into your Mailtrap account to verify your API token.
- Version errors and incompatibility – If you’re receiving errors related to the format or version of the docker-compose-yml file, you need to ensure that its file syntax is compatible with the version of Docker Compose installed on your system. To do this, simply run
docker-compose --version
and compare it with the syntax you used in .yml.- You can also check the official Docker Compose documentation for version-specific syntax and features.
- Network issues and connectivity (Windows & macOS) – If your container cannot connect to external networks, you should check Docker’s network configuration with the built-in troubleshooting tools or manually inspect the settings of your container.
- Make sure that your Docker network allows outbound connection and that no firewall rules are blocking these connections.
- Docker0 connectivity issues (Linux) – Sometimes there may be misconfigurations in the
docker0
bridge network, the default bridge Docker uses to communicate between containers and the host. You can inspect its interface and Docker0 IP by using some of the following commands:
ip a show docker0
- These commands will allow you to verify that the docker0 is up and running and that its IP address does not conflict with your local network and firewall settings.
Test your emails before sending with Mailtrap
When you’re configuring this much code for sending emails from your app, a lot of things can go wrong. For example, your HTML might not render correctly in some email clients so you’ll need a fallback. Your personalization variables might be off, your emails might be getting marked as spam without you knowing it, etc.
Hence, it’s super important to experiment and test your PHP emails before sending them.
Now, although you can test your emails with localhost in Docker, Mailtrap has its official PHP client and email API that provides you with consistency across different development setups and has various advanced features.
With Mailtrap Email Testing, you can safely inspect whether your HTML/CSS has rendered properly in different email clients, as Mailtrap will show you faulty lines of code and display them in your virtual inbox, where you can correct or remove them.
On top of that, Mailtrap checks the spam score of your emails, thanks to which you can prevent a significant amount of deliverability issues if you keep the score below 5.
You can also easily share the testing process with your other team members, create new projects, and even add multiple objects within.
And most importantly, testing emails with Mailtrap is super easy.
SMTP
To start testing, simply navigate to the Email Testing tab, select an inbox, click on SMTP settings, and open Show Credentials. There, you’ll see the credentials of Mailtrap’s fake SMTP servers.
API
Or, you can integrate Mailtrap email testing API with your app using ready-made code snippets and get even more testing flexibility.
You can also use the Testing API for Testing and QA automation.
For more details, read the official Mailtrap API documentation.
Or, check out the video we’ve prepared for you.
Overall, Mailtrap is a platform that can cover all of your email-related needs. You can use it to test your email-sending functionality, send emails with SMTP or with API, and then monitor the performance of your email infrastructure with in-depth analytics.
Bonus: Testing your emails using GitHub repositories
Additionally, a few Mailtrap users and developers made GitHub repositories, which provide you with Docker images for testing via Mailtrap’s email sandbox.
Much thanks to Dennis Böckmann and David Bătrânu for making them. 🙂
The original Mailtrap Docker image, developed by Eau de Web, lets you catch all mail and display it in a roundcube interface. You can find it here.
Since EDW is a bit outdated, I’ll show you how to use DBCK’s repository.
DBCK
Inspired by Eau de Web, DBCK’s repository is your go-to choice if you’re looking for a solution that provides you with a catch all email server for development with SMTP, IMAP, and webmail support.
It also allows you to access the Mailtrap web interface to view and manage the emails sent from your application.
Here’s the GitHub repository, and here’s how to use it:
1. Clone or download the repository
Either clone the repository to your local machine by downloading the repository as a ZIP file or run the following command in a terminal if you’re using Git:
git clone https://github.com/dbck/docker-mailtrap.git
2. Run the Docker container
- To start the Mailtrap container with basic port mappings, run:
docker container run -d --rm --init --name=mailtrap -p 127.0.0.1:9080:80 -p 127.0.0.1:9025:25 dbck/mailtrap
- To start the Mailtrap container with all available ports mapped, run:
docker container run -d --rm --init --name=mailtrap -p 127.0.0.1:9080:80 -p 127.0.0.1:9025:25 -p 127.0.0.1:9587:587 -p 127.0.0.1:9465:465 -p 127.0.0.1:9143:143 -p 127.0.0.1:9993:993 dbck/mailtrap
3. Configure your application
Set the SMTP server address to localhost
or the IP address of your Docker host if you’re running Docker in a virtual machine or on a remote server.
You also need to set the port to the one specified in the command you used to run the container (e.g., 25, 465, 587, etc.).
Then, you can access the Mailtrap web interviews and view/manage the emails sent from your application. The default URL for the Mailtrap web interface is http://localhost:9080
.
4. Check the logs (optional)
Once you’re done, you can monitor the activity of the Mailtrap container with a docker logs
command:
docker logs -f mailtrap
For more information, consult the GitHub repository.
Wrapping up
And this wraps up our “Docker send email” guide!
If you don’t need advanced features and flexibility, then you’ll want to send your emails with SMTP.
But, if you want more security features and want to send higher volumes of emails, then go for email API.
And if you’re looking for more content related to sending emails in various languages and frameworks other than PHP, be sure to check the Mailtrap blog, where you can read articles such as: