How to Install Mailtrain v2 on Ubuntu 20.04 Server

This tutorial will show you how to install Mailtrain v2 on Ubuntu 20.04 without Docker. Mailtrain is an open-source self-hosted newsletter app, an alternative to commercial email service providers like Mailchimp. You can use Mailtrain to send emails to your email subscribers via your own email server or by using any SMTP relay service (Sendinblue, SendGrid, AmazonSES, Mailgun, etc).

Mailtrain is released under the terms of GPL v3.0 license, built on Node.js and MySQL/MariaDB. The latest version is v2, released on June 2021. Features of Mailtrain are as follows:

  • It allows you to easily manage large mailing lists (like 1 million subscribers).
  • You can add subscribers manually, through the API, or import from a CSV file.
  • It supports custom fields (text fields, numbers, drop-downs or checkboxes), merge tags and custom forms.
  • List segmentation.
  • RSS campaign: auto-generate newsletter from RSS feed and send it to subscribers.
  • Subscribers can upload their GPG public keys and Mailtrain will encrypt the newsletter for them.
  • It allows you to check individual click statistics for every link.
  • Advanced email template editors and HTML code editor.
  • Automation: send specific emails when user activates your predefined trigger.
  • You can create an open email list (allow public subscription) and closed email list (subscribers are added to the list by admin).
  • Create multiple users with granular user permissions and flexible sharing.
  • Hierarchical namespaces for enterprise-level situations
  • Localize the user interface per user
  • List export
  • Ability to send to multiple lists with prevention of double delivery.
  • Multiple send configurations
  • SMTP Throttling to prevent your server from sending a large volume of emails in a short amount of time, which will improve email deliverability.

How to Install Mailtrain v2 on Ubuntu 20.04 Server

Step 1: Choose the Right Hosting Provider

Self-hosting can save you a lot of money. Mailtrain is free and open-source software. You only need to pay $26/month for the VPS (virtual private server), which can run a full-featured mail server and the Mailtrain email marketing platform. It can easily handle millions of subscribers. So your total cost is always $26/month no matter how many subscribers you have. If you own millions of subscribers on MailChimp, the cost would be thousands of dollars per month.

It’s not an easy task to find a VPS (Virtual Private Server) provider suitable for email hosting and email marketing. Many hosting companies like DigitalOcean blocks port 25. DigitalOcean would not unblock port 25, so you will need to set up SMTP relay to bypass blocking, which can cost you additional money. If you use Vultr VPS, then port 25 is blocked by default. They can unblock it if you open a support ticket, but they may block it again at any time if they decide your email sending activity is not allowed. Vultr actually may re-block it if you use their servers to send newsletters.

Another problem is that big well-known hosting providers like DigitalOcean or Vultr are abused by spammers. Often the server IP address is on several blacklists. Vultr has some entire IP ranges blacklisted.

ScalaHosting is a very good option to run a mail server because

  • They don’t block port 25.
  • The IP address isn’t on any email blacklist. (At least this is true in my case. I chose the Dallas data center.) You definitely don’t want to be listed on the dreaded Microsoft Outlook IP blacklist or the SpamRats blacklist. Some blacklists block an entire IP range and you have no way to delist your IP address from this kind of blacklists.
  • You can edit PTR record to improve email deliverability.
  • They allow you to send newsletters to your email subscribers with no hourly limits or daily limit, whatsoever. Note that you are not allowed to send spam, also known as unsolicited bulk email. If the recipient doesn’t explicitly give you permission to send emails, and you send emails to them, that’s unsolicited email.

I recommend following the tutorial linked below to properly set up a Linux VPS server on ScalaHosting. Use coupon code linuxbabe2021 on ScalaHosting payment page to save $100 if you choose to pay 12 months upfront.

You also need a domain name. I registered my domain name from NameCheap because the price is low and they give you whois privacy protection free for life.

If you don’t have your own mail server yet, I recommend using the free iRedMail program to quickly set up your own mail server before installing Mailtrain, so you don’t have to spend money on commercial SMTP relay service.

Step 2: Add Sudo User

I installed Mailtrain with a sudo user on Ubuntu 20.04. For best results, you should also follow this tutorial with a sudo user, not root. To add a sudo user, simply run the following command on the server

sudo adduser username
sudo adduser username sudo

Then switch to the new user.

su - username

Step 3: Install MariaDB Database Server

Note: If you followed my iRedMail tutorial to set up your email server, then you should already have MariaDB up and running, so you can skip this step.

Your subscribers’ data will be stored in a database. Mailtrain supports MySQL and MariaDB. MariaDB is a drop-in replacement for MySQL. It is developed by former members of MySQL team who are concerned that Oracle might turn MySQL into a closed-source product. So let’s install the MariaDB database server.

Enter the following command to install MariaDB on Ubuntu 20.04.

sudo apt install mariadb-server mariadb-client

After it’s installed, MariaDB server should be automatically started. Use systemctl to check its status.

systemctl status mariadb


 mariadb.service - MariaDB 10.3.22 database server
     Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2020-04-10 14:19:16 UTC; 18s ago
       Docs: man:mysqld(8)
   Main PID: 9161 (mysqld)
     Status: "Taking your SQL requests now..."
      Tasks: 31 (limit: 9451)
     Memory: 64.7M
     CGroup: /system.slice/mariadb.service
             └─9161 /usr/sbin/mysqld

If it’s not running, start it with this command:

sudo systemctl start mariadb

To enable MariaDB to automatically start at boot time, run

sudo systemctl enable mariadb

Now run the post-installation security script.

sudo mysql_secure_installation

When it asks you to enter MariaDB root password, press Enter key as the root password isn’t set yet. Then enter y to set the root password for MariaDB server.


Next, you can press Enter to answer all remaining questions, which will remove anonymous user, disable remote root login and remove test database. This step is a basic requirement for MariaDB database security. (Notice that Y is capitalized, which means it is the default answer. )


Step 4: Create a Database and User for Mailtrain

Run the following command to log into MariaDB console.

sudo mysql -u root

Create a database for Mailtrain using the following command. I named it mailtrainv2, but you can use whatever name you like. (Don’t leave out the semicolon.)

create database mailtrainv2;

Then enter the command below to create a database user for Mailtrain and grant all privileges of the mailtrain database to the user. Replace mailtrain and mailtrain_password with your preferred username and password.

grant all privileges on mailtrainv2.* to mailtrain@localhost identified by 'mailtrain_password';

Flush the privileges table for the changes to take effect and then get out of MariaDB console.

flush privileges;


Step 5: Install Node.js

Mailtrain is built on Node.js, which is a JavaScript run-time environment that translates human-readable JavaScript code into machine code. So we need to install Node.js on Ubuntu in order to run Mailtrain. Mailtrain v2 requires Node.js 14+. This tutorial will install Node.js and the package manager (npm) from the upstream repository.

curl -sL | sudo -E bash -
sudo apt install nodejs

To check your Node.js and npm version, run

node -v

npm -v


mailtrainv2 nodejs 14

Note that I don’t recommend installing the latest LTS version of Node.js (v16) from the repository, because it’s not very compatible with Mailtrain v2.  To compile and install native addons from npm you also need to install build tools:

sudo apt install -y build-essential

To edit images in the email template editor and HTML editors, you need to install ImageMagick.

sudo apt install imagemagick

Step 6: Install Redis Cache

You can install Redis server for session cache. This will allow Mailtrain to run 5 processes instead of the default single process, which will speed up email delivery if you have lots of email subscribers (Note that this will increase the memory usage like about 250MB).

sudo apt install redis

After it’s installed, Redis should be automatically started. You can check its status with:

systemctl status redis

Sample output:

 redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
     Active: active (running) since Wed 2021-10-27 20:01:10 HKT; 4 days ago
   Main PID: 1359 (redis-server)
      Tasks: 4 (limit: 15514)
     Memory: 10.8M
     CGroup: /system.slice/redis-server.service
             └─1359 /usr/bin/redis-server

If it’s not running, you can start it with:

sudo systemctl start redis

Enable auto-start at boot time:

sudo systemctl enable redis

Step 7: Run Mailtrain

You should be working in your home directory for this step.

cd ~

Then fetch Mailtrain files from Github. (Please do not use sudo when running the git commands.)

sudo apt install git

git clone

cd mailtrain/

git checkout v2

Import the initial SQL data to the mailtrain database by using the following command. You need to enter the password of mailtrain user created in step 4.

mysql -u mailtrain -p mailtrainv2 < ~/mailtrain/server/setup/sql/mailtrain.sql

Create the production.yaml configuration file with a command-line text editor like Nano.

nano ~/mailtrain/server/config/production.yaml

In this file, you can add configurations that override the default configurations in ~/mailtrain/server/config/default.yaml file.  We only need to add the following configurations. Note that there should be a space character after each colon.

user: mailtrain
group: mailtrain
roUser: nobody
roGroup: nobody

  proxy: true
  secret: "Replace this with some random characters"

  user: mailtrain
  password: mailtrain_password
  database: mailtrainv2
  enabled: true

  level: info

  enabled: false

  processes: 5

Mailtrain requires you to use 3 URL endpoints.

  • The trusted URL used by logged-in users.
  • This is used to host template editors, not shown to any user.
  • The public URL as seen by visitors.

Save and close the file. Then create the mailtrain user and group for the mailtrain daemon to run as. Note that we don’t need to create password for this user, so we create a system user instead of a normal user.

sudo adduser --system --group --no-create-home mailtrain

Create a configuration file for the report worker.

nano ~/mailtrain/server/services/workers/reports/config/production.yaml

Add the following configurations.

  level: warn
  user: mailtrain
  password: mailtrain_password
  database: mailtrainv2

Save and close the file.

Now make sure you are in the ~/mailtrain/ directory.

cd ~/mailtrain

install the required node packages. The following is a single command. Please do not use sudo.

for idx in client shared server mvis/client mvis/server mvis/test-embed mvis/ivis-core/client mvis/ivis-core/server mvis/ivis-core/shared mvis/ivis-core/embedding; do
(cd $idx && npm install)

If you encounter the following error message, you can ignore them.

-bash: cd: mvis/ivis-core/client: No such file or directory
-bash: cd: mvis/ivis-core/server: No such file or directory
-bash: cd: mvis/ivis-core/shared: No such file or directory
-bash: cd: mvis/ivis-core/embedding: No such file or directory

Change to the ~/mailtrain/client/ directory.

cd ~/mailtrain/client

Build the node packages.

npm run build

Copy the mailtrain folder to /var/www/.

sudo mkdir -p /var/www/

cd ~

sudo cp ~/mailtrain /var/www/mailtrainv2 -r

Then change the permission of /var/www/mailtrainv2/.

sudo chown mailtrain:mailtrain /var/www/mailtrainv2/ -R

sudo chmod o-rwx /var/www/mailtrainv2/server/config/

Create a systemd service unit file for mailtrain.

sudo nano /etc/systemd/system/mailtrainv2.service

Add the following lines to this file.

Description=Mailtrain server mariadb.service redis-server.service

ExecStart=/usr/bin/node index.js


Save and close this file. Then start mailtrainv2.service.

sudo systemctl enable --now mailtrainv2.service

Check its status. Make sure it is running.

sudo systemctl status mailtrainv2.service

Sample output:

 mailtrainv2.service - Mailtrain server
     Loaded: loaded (/etc/systemd/system/mailtrainv2.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2021-11-01 16:42:10 HKT; 8s ago
   Main PID: 2794663 (mailtrain)
      Tasks: 25 (limit: 15514)
     Memory: 258.0M
     CGroup: /system.slice/mailtrainv2.service
             ├─2794663 mailtrain
             ├─2794693 mailtrain: worker executor
             └─2794701 /usr/bin/node /var/www/mailtrainv2/server/services/importer.js

If it’s not running, you can check the log.

sudo journalctl -eu mailtrainv2

If mailtrainv2.service is running, you can check which ports it’s using with the following command.

sudo netstat -lnpt | grep mailtrain

Step 8: Setting up Reverse Proxy

We can use Nginx or Apache web server to set up the reverse proxy.


If you use iRedMail, then you should choose Nginx.

Install Nginx web server.

sudo apt install nginx

Create 3 Nginx virtual hosts for the 3 URL endpoints.

sudo nano /etc/nginx/sites-enabled/
sudo nano /etc/nginx/sites-enabled/
sudo nano /etc/nginx/sites-enabled/

The content of the 3 files are as follows:

server {
        listen 80;

        access_log /var/log/nginx/mailtrain.access;
        error_log /var/log/nginx/mailtrain.error;

       location / {
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

server {
        listen 80;

        access_log /var/log/nginx/sbox-mailtrain.access;
        error_log /var/log/nginx/sbox-mailtrain.error;

       location / {
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

server {
        listen 80;

        access_log /var/log/nginx/newsletter.access;
        error_log /var/log/nginx/newsletter.error;

       location / {
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Save and close the files. Then test Nginx configurations.

sudo nginx -t

If the test is successful, reload Nginx.

sudo systemctl reload nginx


Install Apache web server.

sudo apt install apache2

Create 3 Apache virtual hosts for the 3 URL endpoints.

sudo nano /etc/apache/sites-enabled/
sudo nano /etc/apache/sites-enabled/
sudo nano /etc/apache/sites-enabled/

The content of the 3 files are as follows:

<VirtualHost *:80>
    ServerSignature Off

    ProxyPreserveHost On
    ProxyPass /
    ProxyPassReverse /

    ErrorLog /var/log/apache2/

<VirtualHost *:80>
    ServerSignature Off

    ProxyPreserveHost On
    ProxyPass /
    ProxyPassReverse /

    ErrorLog /var/log/apache2/

<VirtualHost *:80>
    ServerSignature Off

    ProxyPreserveHost On
    ProxyPass /
    ProxyPassReverse /

    ErrorLog /var/log/apache2/

Save and close the files. You need to enable 3 modules in Apache.

sudo a2enmod proxy proxy_http headers

Then enable the 3 virtual hosts.

sudo a2ensite

Restart Apache web server.

sudo systemctl restart apache2

Step 6: Enable HTTPS

To encrypt the HTTP traffic when you visit Plex server from outside, we can enable HTTPS by installing a free TLS certificate issued from Let’s Encrypt. Run the following command to install Let’s Encrypt client (certbot) on Ubuntu.

sudo apt install certbot

If you use Nginx web server, you also need to install the Certbot Nginx plugin.

sudo apt install python3-certbot-nginx

Then run the following 3 command to obtain and install TLS certificate.

sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d

sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d

sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d

If you use Apache web server, you also need to install the Certbot Apache plugin.

sudo apt install python3-certbot-apache

Then run the following command to obtain and install TLS certificate.

sudo certbot --apache --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d
sudo certbot --apache --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d
sudo certbot --apache --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d


  • --nginx: Use the nginx plugin.
  • --apache: Use the Apache plugin.
  • --agree-tos: Agree to terms of service.
  • --redirect: Force HTTPS by 301 redirect.
  • --hsts: Add the Strict-Transport-Security header to every HTTP response. Forcing browser to always use TLS for the domain. Defends against SSL/TLS Stripping.
  • --staple-ocsp: Enables OCSP Stapling. A valid OCSP response is stapled to the certificate that the server offers during TLS.
  • --email: Your email address, which is used for account recovery and other important notification messages.

The certificate should now be obtained and automatically installed.

mailtrain v2 https

Now you should edit the /var/www/mailtrainv2/server/config/production.yaml file and change http to https. Then restart mailtrain service.

sudo systemctl restart mailtrainv2

Step 7: Mailtrain Configuratin

Go to Login with username admin and password test.

mailtrain v2 admin login

Then go to Administration -> Users page to change your account email address and password.

Note: The admin account is an easy target for hackers. For best security, it’s recommended that you change the username from admin to something else. The Mailtrain web interface doesn’t provide such option, but you can change the username in MariaDB database using SQL command.

Go to Administration -> Global Settings page to change default configurations. You should change the service address from http://localhost:3000/ to your sub-domain (

Next, go to Administration -> send configurations to configure SMTP settings, so your Mailtrain can send emails. By default, Mailtrain is configured to use ZoneMTA. Click the Edit button to change the default setting.

mailtrain v2 SMTP settings

In the Mailer Settings, you can use SMTP if you have your own email server or use Amazon SES. Actually, you can also use other SMTP relay services in the SMTP tab. In the screenshot below, I use my own email server. Emails will be submitted on port 587 with STARTTLS encryption.

mailtrain v2 generic SMTP

If Mailtrain is installed on your email server, then you should use the following SMTP settings. The hostname should be and port should 25. There’s no need to enable encryption or authentication when talking to localhost.

mailtrain v2 smtp settings no encryption and authentication

Save your settings. Then you can create a list to test the functionalities of Mailtrain.

Managing Users and Roles

Mailtrain v2 supports multiple users with granular user permissions and flexible sharing. You can create additional users in the Mailtrain web interface. By default, there are 3 roles a user can take.

  • Global master: This is the super admin user.
  • Campaign admin
  • None

Permissions associated with each role is defined in the /var/www/mailtrainv2/server/config/default.yaml file.

Wrapping Up

I hope this tutorial helped you install Mailtrain v2 on Ubuntu 20.04. You can go to Mailtrain wiki to find more information on using Mailtrain. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks. Take care 🙂

Rate this tutorial
[Total: 0 Average: 0]

10 Responses to “How to Install Mailtrain v2 on Ubuntu 20.04 Server

  • thanks buddy, great job, i test it today by installing on a proxmox LXC.

    If I see something I will write to you.

    Thank you so much

  • Hi,

    thanks a lot for this tutorial, very helpful!.
    I’m facing two issues when trying to install node packages, here are the errors. Any idea on how to solve this ?

    npm ERR! prepareGitDep 1> 
    npm ERR! prepareGitDep > [email protected] prepare /home/localadmin/.npm/_cacache/tmp/git-clone-bc4c7630
    npm ERR! prepareGitDep > node -r esm build.js
    npm ERR! prepareGitDep 
    npm ERR! prepareGitDep 
    npm ERR! prepareGitDep 2> npm WARN install Usage of the `--dev` option is deprecated. Use `--also=dev` instead.
    npm ERR! prepareGitDep file:///home/localadmin/.npm/_cacache/tmp/git-clone-bc4c7630/build.js:1
    npm ERR! prepareGitDep SyntaxError: Error parsing /home/localadmin/.npm/_cacache/tmp/git-clone-bc4c7630/node_modules/fs-extra/package.json: Unexpected token , in JSON at position 2565
    npm ERR! prepareGitDep     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10) {
    npm ERR! prepareGitDep   path: '/home/localadmin/.npm/_cacache/tmp/git-clone-bc4c7630/node_modules/fs-extra/package.json'
    npm ERR! prepareGitDep }
    npm ERR! prepareGitDep npm ERR! code ELIFECYCLE
    npm ERR! prepareGitDep npm ERR! errno 1
    npm ERR! prepareGitDep npm ERR! [email protected] prepare: `node -r esm build.js`
    npm ERR! prepareGitDep npm ERR! Exit status 1
    npm ERR! prepareGitDep npm ERR! 
    npm ERR! prepareGitDep npm ERR! Failed at the [email protected] prepare script.
    npm ERR! prepareGitDep npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    npm ERR! prepareGitDep 
    npm ERR! prepareGitDep npm ERR! A complete log of this run can be found in:
    npm ERR! prepareGitDep npm ERR!     /home/localadmin/.npm/_logs/2021-11-05T07_25_20_811Z-debug.log
    npm ERR! prepareGitDep 
    make: *** [ Release/] Error 1
    make: Leaving directory '/home/localadmin/mailtrain/server/node_modules/posix/build'
    gyp ERR! build error 
    gyp ERR! stack Error: `make` failed with exit code: 2
    gyp ERR! stack     at ChildProcess.onExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
    gyp ERR! stack     at ChildProcess.emit (events.js:400:28)
    gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:282:12)
    gyp ERR! System Linux 5.4.0-89-generic
    gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
    gyp ERR! cwd /home/localadmin/mailtrain/server/node_modules/posix
    gyp ERR! node -v v14.18.1
    gyp ERR! node-gyp -v v5.1.0
    gyp ERR! not ok
    • Use a clean fresh server.

      • Caramboleyo
        2 months ago

        Having the same issue on multiple servers – old or new. Had to install build-essentials (?!) because make was not found.
        Now i get this errors too. Seems like mailtrain is a failed project now. Dependencies with over 1800 npm packages and 1GB of disk space for sending email. Insane!

  • But it is a clean new virtual machine …

  • thank you for the good setup manual. I have a question about what you say:

    Create the production.toml configuration file with a command-line text editor like Nano.

    nano ~/mailtrain/server/config/production.yaml

    you say create a .toml file but the command creates a yaml file. Wich one is it?

  • Hi,
    When trying to install apache2 (with your step) it is failing to start. What should I do now?

    • If you installed Nginx, then you should not install Apache. Remove Apache with:

      sudo apt remove apache2
      • Lutfar Rahman
        2 months ago

        Thanks man. I have done it. Can you please tell me how to update mailtrainv2 to latest build? Also is therey any userguide to use mailtrain? Their wiki is not yet in v2. Thanks in advance.

  • Cheerz,

    great tutorial, as always! Thank you!

    One small error:

    Step 6:

    sudo certbot –nginx –agree-tos –redirect –hsts –staple-ocsp –email [email protected] -d

    should be

    sudo certbot –nginx –agree-tos –redirect –hsts –staple-ocsp –email [email protected] -d

    and equivalent for apache.

    And one small improvement maybe…

    Permissions are wrong for:

    fix with:
    sudo chown -R mailtrain:mailtrain mailtrainv2/server/files/

Leave a Comment

  • Comments with links are moderated by admin before published.
  • Your email address will not be published.
  • Use <pre> ... </pre> HTML tag to quote the output from your terminal/console.
  • Please use the community ( for questions unrelated to this article.
  • I don't have time to answer every question. Making a donation would incentivize me to spend more time answering questions.

The maximum upload file size: 2 MB. You can upload: image. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here