INDEX:
Phase 1 - Executive Summary
Phase 2 - Prerequisites
Phase 3 - Deploy A Server
Phase 4 - Core Server Configuration
Phase 5 - Deploy an Apache website
Phase 6 - Full Stack Server Configuration
Phase 7 - Using WordPress as an Integrated FTP
Phase 8 - Install SMTP Mail Server
I just made a script which can be found here :
https://github.com/LanceTreyark/Springb0ard
here is the script:
https://github.com/LanceTreyark/Springb0ard/blob/main/Springb0ard_v2_BetaMax/start.sh
Be Advised,
The process below is antiquated.
The System I went with is made from 2 programs
Postfix & Dovecot
If you just want to setup mail for WordPress all you need is a google workspace account and a plugin like https://fluentsmtp.com/ I’ll probably do a write up on that at a later time.
SECTION 1: Overview
SECTION 2: DNS
SECTION 3: SOFTWARE
SECTION 4: SOURCES
SECTION 1: Overview
Update 3.15.23
I started writing this section in December of 2022. I had to hold off for awhile because the the source material I was using to build the server was incomplete and the server was not stable. I spent 3 months mastering this email server and even wrote a custom installer in shell script to do everything you will need done automatically, but we still need to break each step down and explain what is happening & why.
Here are the necessary procedures required to make a functional email server
Get UpCloud or your cloud host to open port 25
Configure your DNS Records through your DNS providers site
Configure your reverse DNS records through UpCloud’s Network Utility
Acquire SSL Certificate for the mailServer to use for encryption
Install & configure Postfix
Install & configure Dovecot
Optional security measures
SECTION 2: DNS
Open Port 25
The first step in building an email server is to request that your hosting provider open port 25 for you. Port 25 is the primary email submission port for an email server & by default most hosting providers have this port closed to prevent email abuse. Opening this port with UpCloud involves messaging tech support & filling out a questionnaire. The form asks what you intentions are, your projected volume of emails, your knowledge of security rules and best practices and if you have an unsubscribe button.
They don’t ask you specific questions or test you for security procedures, you can simply state that you are using Postfix a reputable email software, that you intend to comply with legal regulations outlined in the CAN-SPAM Act and GDPR, that you will be using SSL encryption, you will implement an unsubscribe button & Follow strict anti-spam policies. Personally I also included a link to my developer blog so they knew who they were dealing with. They opened the port for me 15 minutes later!
Here are some email server admin best practices provided by ChatGPT:
Running an email server requires adherence to certain rules to ensure the proper functioning of the server and the delivery of emails to their intended recipients. Here are some general rules to follow:
Use a reputable email server software: Use a widely accepted email server software such as Postfix, Exim or Microsoft Exchange Server.
Secure your email server: Ensure that your email server is secure by applying security patches regularly, configuring firewalls, and using strong passwords.
Use authentication methods: Use authentication methods such as Sender Policy Framework (SPF), Domain Keys Identified Mail (DKIM), and Domain-based Message Authentication, Reporting, and Conformance (DMARC) to prevent email spoofing.
Avoid spamming: Follow strict anti-spam policies to prevent spamming, such as limiting the number of emails that can be sent in a given time period and blocking IP addresses associated with spamming.
Monitor your email server: Regularly monitor your email server to detect any suspicious activity or unusual traffic patterns.
Keep a clean mailing list: Make sure your mailing list only includes valid and current email addresses to prevent bouncing and spam complaints.
Respect recipient preferences: Honor recipient preferences for opting-out or unsubscribing from your mailing list.
Comply with legal regulations: Comply with legal regulations such as the CAN-SPAM Act and GDPR to avoid legal repercussions.
Have a backup plan: Regularly backup your email server to prevent loss of data in case of an emergency or technical failure.
Note that these are just some general rules, and specific requirements may vary depending on your email server software and the regulations in your country or region. It's important to research and comply with all applicable rules and best practices for running an email server.
Creating DNS records
The second step in setting up a trustworthy email server is to create the required domain name and mail exchanger records.
The records that you will need to configure:
DNS A record, that maps your domain name to the server’s public IP address.
MX record, which will tell other mail servers where messages send to your domain should be delivered.
Reverse DNS record, that allows servers to check what domain your server’s IP address belongs to.
an SPF record which is technically a TXT record
Set Up “A” Record
in name.com navigate to the manage DNS records page and create your mail server name I’m going to use another domain for this test because at the time of writing this I have archiveninja.com linked to the mx records for google workspace and I don’t want to modify those. For this example I will use arkmail.im which will end up looking like lance@arkmail.im
enter the record as shown:
Record Type Host Answer
A example.com yourServerIP
MX Record:
Note: whenever you see ‘@’ used as the host it just means use the domain without a subdomain, so in this case ‘@’
means ‘arkmail.im’
Record Type Host Answer
MX example.com mail.example.com
SPF records
We will add this after we get the SSL certificate
Reverse DNS records
Log into UpCloud and select “Servers” in the left menu
First let’s rename the server to mail.arkmail.com as shown below. Modify Server Name & Host Name
Next in the left menu select “Network”
Edit the Reverse DNS name for both fields below “REVERSE DNS NAME“ This will tie both the IPV4 and IPV6 records to the mail server.
SECTION 3: SOFTWARE
Preliminary setup:
Make sure domain configurations on the server are correct. First declare the server hostname:
sudo hostname mail.arkmail.im
check to make sure it took with:
hostname
it should return the value: mail.arkmail.im
Next run:
sudo nano /etc/hosts
Add your domain like I’ve shown here:
127.0.0.1 localhost mail.arkmail.im
# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
when your finished run:
sudo systemctl restart networking
sudo systemctl restart apache2
Installing Postfix:
SSH into your server:
ssh samson@95.111.214.118
Postfix is the default MTA for Ubuntu and can be installed directly with the package manager. Use the following command to install the required packages.
sudo apt install postfix
Once the installation is complete, the setup will run a configuration script that asks to define a few settings, select “Internet Site” and use the “Tab“ key to highlight the “<ok>” option. Press “Enter” to continue.
On the next window for “System mail name” – Replace the <example.com> with your domain name: (omit any subdomain like mail.example.com and just use example.com)
With Postfix installed, run the full configuration script to define the settings as below.
The first two pages are identical to the initial install you just did.
sudo dpkg-reconfigure postfix
Again, General type of mail configuration: Internet Site
Again, Already set up- System mail name – Replace the <example.com> with your domain name:
Root and postmaster mail recipient – Any Unix user account: (samson in my case)
Other destinations to accept mail for – Include $mydomain as the first destination:
Force synchronous updates on mail queue? NO
Local networks, Keep Default:
127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
Mailbox size limit (bytes): Default “0”
Local address extension character: Default “+”
Internet protocols to use: ALL
The configuration is written into the /etc/postfix/main.cf file. In case you want to make changes to the above settings, you can always run the reconfiguration script again.
By default, Postfix uses the mbox mailbox format. Another commonly used option is Maildir which stores emails in individual files reducing the chance of your mail database getting corrupted. The following settings will use Maildir but you are free to choose any format. If you wish to use something else, remember to also configure it for Dovecot.
Rather than editing the configuration file directly, you can use the postconf -e command to edit the Postfix parameters in place.
sudo postconf -e 'home_mailbox = Maildir/'
Using the Maildir mailbox format emails are stored in under the recipient user’s home folder /home/<username>/Maildir.
Also, tell Postfix what domain it is the final destination for so that it can be easily referenced as a Postfix variable as was already shown in the configuration script.
sudo postconf -e 'mydomain = arkmail.im'
Now that Postfix is installed, you can continue below with further configurations.
Deploy TLS/SSL Certificate
An easy way to get a certificate issued on a mail server that does not have an Apache config file tied to the domain is to use the client with the --standalone plug-in.
Run the process with this command:
sudo certbot certonly --standalone -d arkmail.im
If everything worked correctly you’ll get a message that HTTPS was successfully enabled.
Once you have finished the process, the certificates will be stored under /etc/letsencrypt/live/<your.domain>/. You can add your new certificates to the Postfix configuration using the two commands below. Replace the <your.domain> with your email server’s domain name.
sudo postconf -e 'smtpd_tls_cert_file = /etc/letsencrypt/live/arkmail.im/fullchain.pem'
sudo postconf -e 'smtpd_tls_key_file = /etc/letsencrypt/live/arkmail.im/privkey.pem'
With the certificate installed, you can configure the rest of the email server.
Setting up SMTP authentication
Next, you should enable SMTP-AUTH, which allows a client to identify itself through the authentication mechanism SASL. Transport Layer Security (TLS) should be used to encrypt the authentication process. Once authenticated, the server will allow the client to relay mail.
Enter the following edits as they are.
sudo postconf -e 'smtpd_sasl_type = dovecot'
sudo postconf -e 'smtpd_sasl_path = private/auth'
sudo postconf -e 'smtpd_sasl_local_domain ='
sudo postconf -e 'smtpd_sasl_security_options = noanonymous'
sudo postconf -e 'broken_sasl_auth_clients = yes'
sudo postconf -e 'smtpd_sasl_auth_enable = yes'
sudo postconf -e 'smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination'
Then configure Postfix to provide TLS encryption for both incoming and outgoing mail.
sudo postconf -e 'smtp_tls_security_level = may'
sudo postconf -e 'smtpd_tls_security_level = may'
sudo postconf -e 'smtp_tls_note_starttls_offer = yes'
sudo postconf -e 'smtpd_tls_loglevel = 1'
sudo postconf -e 'smtpd_tls_received_header = yes'
Enabling the SASL lets users send messages outside the local domain without compromising the security of the relay.
Virtual alias mapping
The last bit of configurations for Postfix is to map the email addresses you wish to use to your user accounts. With virtual alias domains, each hosted address can be aliased to a local UNIX system account or a remote address. Enable virtual alias mapping with the following two edit commands.
sudo postconf -e 'virtual_alias_domains = $mydomain'
sudo postconf -e 'virtual_alias_maps = hash:/etc/postfix/virtual'
You can then create the alias map indicated above. The example below shows how to use this mechanism for the example.com domain. Assign the email addresses you want to enable to a username using the same pattern of <email@domain.com> <username>.
sudo nano /etc/postfix/virtual
postmaster@arkmail.im root
root@arkmail.im root
info@arkmail.im info
Once you have configured the virtual aliases, tell Postfix to generate the required database file from the list.
sudo postmap /etc/postfix/virtual
Then restart Postfix itself to apply the full configuration.
sudo systemctl restart postfix
You might also want to add the Maildir setup to the user home directory template so that it is automatically configured when a new user account is created.
sudo maildirmake.dovecot /etc/skel/Maildir
sudo maildirmake.dovecot /etc/skel/Maildir/.Drafts
sudo maildirmake.dovecot /etc/skel/Maildir/.Sent
sudo maildirmake.dovecot /etc/skel/Maildir/.Trash
sudo maildirmake.dovecot /etc/skel/Maildir/.Templates
The same Maildir can be added to the current user with the commands below. Replace the $USER (or in this case “lance”) with any existing username if that user does not have sudo privileges.
First Let’s create a non sudo user. I’m going to create a user called “lance”
adduser lance
Enter a new password for the user. You can skip the other optional entries like address, room number etc.
if you want to switch to that user you can use the command:
su lance
and enter the pwd. When you want to switch back use the exit command:
exit
This will return to the previous user.
Now make a the mail directory available to the new user:
sudo cp -r /etc/skel/Maildir /home/lance/
In this next example the user ID for lance is 1001, run this command to make sure you have the correct user id for this user:
id -u "lance"
...
output:
...
1001
sudo chown -R 1001:1001 /home/lance/Maildir
sudo chmod -R 700 /home/lance/Maildir
sudo adduser lance mail
Finally, include the Maildir location in your terminal and mail profiles.
echo 'export MAIL=~/Maildir' | sudo tee -a /etc/bash.bashrc | sudo tee -a /etc/profile.d/mail.sh
Relog to the terminal to apply the group changes by reopening the SSH connection.
exit
log back in:
ssh samson@95.111.214.118
Configuring Dovecot
Postfix supports two SASL implementations, that are used for authentication, Cyrus and Dovecot. Of these two, Dovecot is relatively simple to configure and was therefore selected for this guide. To enable Dovecot SASL you will need to install the dovecot-common package. You might also wish to install the Dovecot plugins for IMAP and POP3 to allow connections from mail clients such as Thunderbird or Outlook.
sudo apt install dovecot-common dovecot-imapd dovecot-pop3d
Once installed, you will need to make some changes to a few of the configuration files. Dovecot configuration is split between a number of files under /etc/dovecot/conf.d/. To enable the required security features, make the changes and indicated below to the next four .conf files.
Start by disabling the plaintext authentication at the top and enabling login authentication mechanism near the end of the auth.conf file.
sudo nano /etc/dovecot/conf.d/10-auth.conf
disable_plaintext_auth = yes
...
auth_mechanisms = plain login
Then instruct the mail directory to use the same format as Postfix.
sudo nano /etc/dovecot/conf.d/10-mail.conf
mail_location = maildir:~/Maildir
Next, configure the IMAP and POP3 protocols for email clients in the master.conf file as shown below. Uncomment the port lines shown underneath by deleting ‘#’ sign at the start of these lines. In the same file, also edit the service auth segment to allow user authentication.
sudo nano /etc/dovecot/conf.d/10-master.conf
service imap-login {
inet_listener imap {
port = 143
}
...
}
service pop3-login {
inet_listener pop3 {
port = 110
}
...
}
...
service auth {
...
# Postfix smtp-auth
unix_listener /var/spool/postfix/private/auth {
mode = 0660
user = postfix
group = postfix
}
Most email clients default to the standard ports, 143 for IMAP and 110 for POP3. With STARTTLS required for every connection, there is no need to duplicate the services to the SSL dedicated ports.
You will also need to include your certificates in the Dovecot ssl.conf file, replace the <mail.example.com> with your server’s domain name. Select to require SSL and also disable the insecure SSLv2 and SSLv3 protocols.
sudo nano /etc/dovecot/conf.d/10-ssl.conf
# SSL/TLS support: yes, no, required. <doc/wiki/SSL.txt>
ssl = required
...
ssl_cert = </etc/letsencrypt/live/arkmail.im/fullchain.pem
ssl_key = </etc/letsencrypt/live/arkmail.im/privkey.pem
...
# SSL protocols to use
ssl_protocols = SSLv1
When you are done editing the files, you can check the Dovecot configuration with the following command.
dovecot -n
Once everything looks correct, restart Dovecot to apply the new settings.
sudo systemctl restart dovecot
That is it! Congratulations, your mail server is now ready to receive and send emails using secure authentication.
SPF Record:
Add this record to your DNS settings to avoid being blocked as spam. Replace 000.0.000.0 with your servers IP address
Record Type Host Answer
TXT example.com v=spf1 ip4:000.0.000.0 -all
Here is an example of the final DNS settings for an Apache webServer with a live Postfix email server:
Testing the SMTP server locally
You can test the Postfix server locally from the terminal by using a direct connection with netcat, telnet or similar. The following commands need to be executed in the correct order or the server will close the connection.
nc mail.example.com 25
EHLO $hostname
MAIL FROM:root@arkmail.im
RCPT TO:lance@arkmail.im
DATA
Subject: Test email
Body of the email
.
QUIT
If the configuration worked correctly, you should see a confirmation that the email you just wrote has been placed in the queue and will arrive momentarily.
Note that using this method you can only send emails to your own domain addresses. When attempting to set recipient outside your own domain, you will see a message stating that relay access is denied and the connection will be closed.
Another little more convenient way to use email from the terminal is to install Mailutils.
sudo apt install mailutils
It can be used to check mail with the simple command below.
mail
You can also test sending mail using the same utility by adding the recipient address.
mail lance@arkmail.im
Then complete the email form with subject and body text. Send the message by pressing Ctrl+D which exits the utility. Using this method will allow you to send messages outside your network. However, the sender and return addresses will show your username and server domain name, e.g. root@mail.example.com, instead of the probably more desirable email@domain.com. Therefore this method should only be used for testing purposes.
Additional security options
The main concerns of running a private SMTP server will be combating both incoming and outgoing spam messages. A secure configuration and strong user passwords will help with the latter but you might wish to take additional steps to prevent incoming spam.
Reject bad connections and spam messages
Tightening the rules for SMTP connections can stop many of the common spambots that disregard email etiquette. Requiring a valid HELO or EHLO command with a fully qualified domain name can do just that. Add the following parameters to further improve your secure Postfix configuration.
sudo postconf -e 'smtpd_helo_required = yes'
sudo postconf -e 'smtpd_helo_restrictions = reject_non_fqdn_helo_hostname,reject_invalid_helo_hostname,reject_unknown_helo_hostname'
Postfix supports a verify (VRFY) command which allows anyone to determine if an account exists on the system, which can provide significant assistance to any brute force attack on your user accounts. VRFY may also give out sensitive information about the users, such as the account owners full name. It is recommended to disable the VRFY command with the following parameter.
sudo postconf -e 'disable_vrfy_command = yes'
You might also wish to delay the reject message to allow Postfix to log recipient address information when the connected client breaks any of the reject rules. This allows you to later find out who the spammers were trying to target.
sudo postconf -e 'smtpd_delay_reject = yes'
The Postfix recipient restrictions that were set in the SASL configuration part are important in securing the server while allowing users to connect with email clients such as Thunderbird or Outlook. Keeping these parameters in the right order will retain this ability, but you can include further restrictions that incoming messages will need to comply with.
sudo postconf -e 'smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination,reject_invalid_hostname,reject_non_fqdn_hostname,reject_non_fqdn_sender,reject_non_fqdn_recipient,reject_unknown_sender_domain,reject_rbl_client sbl.spamhaus.org,reject_rbl_client cbl.abuseat.org'
The parameters above are fairly self-explanatory though a little difficult to read in a terminal copy paste friendly format. The general idea is to reject connections from made up addresses that do not use a fully qualified domain name or simply do not exist. Here is possible to also add external spam filters such as the Spamhaus or CBL blacklists. If you wish to find out more, Postfix has a very extensive documentation on its configuration options.
Directing spam to /dev/null
Postfix supports a so-called catch-all address with the virtual aliases. Any emails sent to an address not specified in the virtual map will be directed according to the catch-all address. This is useful to hide the valid addresses by allowing mail delivery to any address hence preventing spammers from finding real users through simple trial and error.
Enable the catch-all address by adding a line as shown in the example below to the end of your virtual mapping without any local part and direct the messages to a virtual user nobody.
sudo nano /etc/postfix/virtual
...
@example.com nobody
To prevent spam from filling up all of your storage space, edit the system aliases list to direct messages sent to invalid addresses straight to /dev/null.
sudo nano /etc/aliases
# See man 5 aliases for format
postmaster: root
nobody: /dev/null
Once you have configured both the system and virtual aliases, tell Postfix to regenerate the required database files from these lists.
sudo postmap /etc/postfix/virtual
sudo postalias /etc/aliases
Then reload Postfix again to enable the new settings.
sudo service postfix reload
You can test the spam trap by sending a message to any random unconfigured email address, the mail should be delivered successfully but will not be stored. Another way to test this is by using an address validator such as the Email Checker, any address should show up as valid, even the none existing ones.
Maintaining security
Configuring and maintaining a secure Postfix SMTP server only requires a basic understanding of the components, but simple mistakes in the setup can render the security settings ineffective, therefore most important part is to make sure the server does not become an open relay. Conveniently MX Toolbox, an online network testing utility, provides an SMTP diagnostics tool with which you can easily test your configuration by just entering your mail server domain name such as mail.example.com. With the setup used in this guide, everything should show green in their tests, granted that the DNS rules have propagated.
While a configuration helps to keep your SMTP server secure, strong user passwords are also very important. In such a case that a third party was to gain unauthorised access to one of the user account, they would be able to send spam messages unhindered using your infrastructure and tarnish your network reputation. A common way to reduce the chance of someone guessing your user’s passwords is to impose limitations to failed logging attempts with Fail2ban. You can read more about install Fail2ban on Ubuntu in its own article to further improve the server security.
General good usage practices can also bring your server security a long way. In addition to the aforementioned security methods, Linux systems offer documentation ways to minimise vulnerabilities and harden your cloud server against abuse. Take a look at our introductory guide on how to secure your Linux cloud server if you wish to learn more.
Using an external SMTP Relay like Google
https://www.howtoforge.com/tutorial/configure-postfix-to-use-gmail-as-a-mail-relay/
INDEX:
Phase 1 - Executive Summary
Phase 2 - Prerequisites
Phase 3 - Deploy A Server
Phase 4 - Core Server Configuration
Phase 5 - Deploy an Apache website
Phase 6 - Full Stack Server Configuration
Phase 7 - Using WordPress as an Integrated FTP
Phase 8 - Install SMTP Mail Server
SECTION 4: SOURCES
Sources:
https://www.howtoforge.com/tutorial/configure-postfix-to-use-gmail-as-a-mail-relay/
https://upcloud.com/resources/tutorials/secure-postfix-using-lets-encrypt
SECTION 5: CODE
This is a shell script that automates the postfix & Dovecot installation
It has been tested and works properly. The repo on github is maintained regularly here is a link to the list of changes with dates:
#!/bin/bash
# nano 0a3a_installPostfix.sh
# sudo chmod +x 0a3a_installPostfix.sh
# ./0a3a_installPostfix.sh
#!!!!!!!!!!!!!!!!!!!! KEEP IN MIND THIS IS A PUBLIC REPO !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<<comment
* TITLE: 0a3a_installPostfix.sh
* AUTHOR: Lance Pierson
* DATE: 3/16/2023
PURPOSE:
This is an automatic SMTP email server installer
As of 3.8.23
My plan is to set this to be able to run independently as it's own program.
This is the initial Postfix configuration
comment
echo "The script is live!"
sleep 1
echo "Creating the Springboard program directory in the /etc directory"
echo ""
echo "---------------------------------------------------------"
echo "Here is the etc directory before the change:"
echo "---------------------------------------------------------"
echo ""
sudo ls /etc
sudo mkdir /etc/springboard
# Give ownership of springboard to my regular user
userID=$(id -u)
sudo chown -R $userID:$userID /etc/springboard
echo "---------------------------------------------------------"
echo ""
echo "Here is the etc directory after the change:"
echo "---------------------------------------------------------"
echo ""
sudo ls /etc
echo "---------------------------------------------------------"
echo ""
read -p "Please enter the domain name to use for this mailserver, Don't add the 'www., mail. or smtp.' just the domain: " mailDomain
read -p "Please create a new username for your new virtual inbound email address: " regMailUser
mkdir /etc/springboard/vArs
touch /etc/springboard/vArs/mailDomain.txt
echo "$mailDomain" >> /etc/springboard/vArs/mailDomain.txt
touch /etc/springboard/vArs/regMailUser.txt
echo "$regMailUser" >> /etc/springboard/vArs/regMailUser.txt
sleep 1
echo "verifying if the variables were stored correctly..."
if [ "$(cat /etc/springboard/vArs/mailDomain.txt)" = "$mailDomain" ] && [ "$(cat /etc/springboard/vArs/regMailUser.txt)" = "$regMailUser" ]
then
echo "Great, the variables were stored correctly"
else
echo "There is a problem with a mismatch between the contents of this programs text files and the variables.."
read -p "would you like to continue?" xVar
fi
sleep 1
echo "Opening required mail ports..."
sudo ufw allow 25
sudo ufw allow 143
sudo ufw allow 110
sudo ufw allow 554
sudo ufw allow "WWW Full"
sudo ufw status
echo "Adding new user $regMailUser"
read -p "Press enter to continue" xVar
sleep 1
sudo adduser $regMailUser
sleep 1
echo "Next we will set up the server name and IP so that the Mail DNS is in order..."
sudo hostname mail.$mailDomain
hostName=$(hostname)
echo "The Hostname for this server is set to $hostName"
#
# added \/ 3.16.23
# Assign IP to variable:
myIPv4=$(ip addr show | awk '{if (match($2,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/)) {print $2}}' | head -2 | tail -1)
cat >/tmp/ipSort3r.txt <<EOF
$myIPv4
EOF
myIP=$(awk -F/ '{print $1}' /tmp/ipSort3r.txt)
echo "The IP address for this server is: $myIP"
# removing tmp file
sudo rm -r /tmp/ipSort3r.txt
echo "Add Host data to the end of hosts file:"
sleep 1
echo "We are going to add the domain name to the hosts file"
sleep 1
echo "here is the file currently:"
sleep 1
echo "------------------------------------------------------"
sudo cat /etc/hosts
echo "------------------------------------------------------"
read -p "press enter to ammend it to '127.0.0.1 localhost mail.$mailDomain'" meh
sudo sed -i "/127.0.0.1/a $myIP mail.$mailDomain" /etc/hosts
echo ""
sleep 1
echo "Okay here is the amended file:"
echo "------------------------------------------------------"
sudo cat /etc/hosts
echo "------------------------------------------------------"
echo ""
sleep 1
# added /\ 3.16.23
#
echo "setting up Pre-Seeding Parameters for automatic postfix installation..."
sleep 1
echo "before seed file in /tmp"
ls -a -1 /tmp/
sleep 1
touch /tmp/postfix.seed
echo "After seed file in /tmp"
ls -a -1 /tmp/
sleep 2
echo "postfix postfix/main_mailer_type string 'Internet Site'" >> /tmp/postfix.seed
echo "postfix postfix/mailname string $mailDomain" >> /tmp/postfix.seed
echo "/var/cache/debconf/ before mv"
ls -a -1 /var/cache/debconf/
sleep 2
sudo mv /tmp/postfix.seed /var/cache/debconf/
echo "/var/cache/debconf/ After file mv"
sleep 2
echo "verify contents"
cat /var/cache/debconf/postfix.seed
sleep 2
########################
# Postfix Installation #
########################
echo "Install & Preconfigure Postfix"
sudo debconf-set-selections /var/cache/debconf/postfix.seed
sudo apt install postfix -y
read -p "Press enter to continue" xVar
# If I wanted to split this into another script add this part so the variables are imported:
# mailDomain=$(cat /etc/springboard/vArs/mailDomain.txt)
# regMailUser=$(cat /etc/springboard/vArs/regMailUser.txt)
echo "Configuring Postfix..."
sudo postconf -e 'home_mailbox = Maildir/'
sudo postconf -e "mydomain = $mailDomain"
# forgot to add cerbot install -may need to try preseeding this?
sudo apt install certbot -y
echo "creating standalone certificate for the email"
read -p "Make sure you have your DNS ready then press enter to continue" xVar
sudo certbot certonly --standalone -d mail.$mailDomain
sudo postconf -e "smtpd_tls_cert_file = /etc/letsencrypt/live/mail.$mailDomain/fullchain.pem"
sudo postconf -e "smtpd_tls_key_file = /etc/letsencrypt/live/mail.$mailDomain/privkey.pem"
echo "installing Dovecot"
read -p "Press enter to continue" xVar
sudo apt install dovecot-common dovecot-imapd dovecot-pop3d -y
sudo postconf -e 'smtpd_sasl_type = dovecot'
sudo postconf -e 'smtpd_sasl_path = private/auth'
sudo postconf -e 'smtpd_sasl_local_domain ='
sudo postconf -e 'smtpd_sasl_security_options = noanonymous'
sudo postconf -e 'broken_sasl_auth_clients = yes'
sudo postconf -e 'smtpd_sasl_auth_enable = yes'
sudo postconf -e 'smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination'
sudo postconf -e 'smtp_tls_security_level = may'
sudo postconf -e 'smtpd_tls_security_level = may'
sudo postconf -e 'smtp_tls_note_starttls_offer = yes'
sudo postconf -e 'smtpd_tls_loglevel = 1'
sudo postconf -e 'smtpd_tls_received_header = yes'
sudo postconf -e "mydestination = $mydomain, $myhostname, localhost.$myhostname, localhost"
sudo postconf -e "myhostname = mail.$mailDomain"
sudo postconf -e 'virtual_alias_maps = hash:/etc/postfix/virtual'
sudo postconf -e 'sender_canonical_maps = regexp:/etc/postfix/sender_canonical'
touch /tmp/sender_canonical
echo "/$regMailUser@mail.$mailDomain/ $regMailUser@$mailDomain" >> /tmp/sender_canonical
sudo cp /tmp/sender_canonical /etc/postfix/
sudo postmap /etc/postfix/sender_canonical
touch /tmp/virtual
echo "postmaster@$mailDomain root" >> /tmp/virtual
echo "root@$mailDomain root" >> /tmp/virtual
echo "info@$mailDomain info" >> /tmp/virtual
sudo cp /tmp/virtual /etc/postfix/ # <-delete tmp file later
sudo postmap /etc/postfix/virtual
sudo sed -i "/#smtps inet n - y - - smtpd/a smtps inet n - y - - smtpd" /etc/postfix/master.cf
sudo systemctl restart postfix
sudo maildirmake.dovecot /etc/skel/Maildir
sudo maildirmake.dovecot /etc/skel/Maildir/.Drafts
sudo maildirmake.dovecot /etc/skel/Maildir/.Sent
sudo maildirmake.dovecot /etc/skel/Maildir/.Trash
sudo maildirmake.dovecot /etc/skel/Maildir/.Templates
sudo cp -r /etc/skel/Maildir /home/$regMailUser/
uid=$(id -u "$regMailUser")
sudo chown -R $uid:$uid /home/$regMailUser/Maildir
sudo chmod -R 700 /home/$regMailUser/Maildir
sudo adduser $regMailUser mail
echo 'export MAIL=~/Maildir' | sudo tee -a /etc/bash.bashrc | sudo tee -a /etc/profile.d/mail.sh
sleep 1
echo "Phase 1 Postfix configuration is complete"
sleep 1
########################
# Dovecot Installation #
########################
echo "Starting Dovecot Installation..."
sleep 1
echo "Press Enter to continue..."
echo "Editing /etc/dovecot/conf.d/10-auth.conf..."
sleep 1
echo "Disable the plaintext authentication & enable the login authentication mechanism"
echo ""
sleep 0.5
echo "disable_plaintext_auth = yes"
echo "..."
echo "auth_mechanisms = plain login"
sleep 1
sudo sed -i "/#disable_plaintext_auth = yes/a disable_plaintext_auth = yes" /etc/dovecot/conf.d/10-auth.conf
# comment out this line
sudo sed -i "s/auth_mechanisms = plain/#auth_mechanisms = plain/" /etc/dovecot/conf.d/10-auth.conf
# Add this line right below it
sudo sed -i "/#auth_mechanisms = plain/a auth_mechanisms = plain login" /etc/dovecot/conf.d/10-auth.conf
sleep 1
echo ""
echo "Instruct the mail directory to use the same format as Postfix."
echo "Editing /etc/dovecot/conf.d/10-mail.conf..."
echo ""
sleep 1
echo ""
echo "Configure the IMAP and POP3 protocols for email clients in the master.conf file "
echo ""
sudo sed -i "s/#port = 143/port = 143/" /etc/dovecot/conf.d/10-master.conf
sudo sed -i "s/#port = 110/port = 110/" /etc/dovecot/conf.d/10-master.conf
sudo sed -i "s/#unix_listener \/var\/spool\/postfix\/private\/auth {/unix_listener \/var\/spool\/postfix\/private\/auth {/" /etc/dovecot/conf.d/10-master.conf
sudo sed -i "/unix_listener \/var\/spool\/postfix\/private\/auth {/a #i7" /etc/dovecot/conf.d/10-master.conf
sudo sed -i "/#i7/a }" /etc/dovecot/conf.d/10-master.conf
sudo sed -i "/#i7/a user = postfix" /etc/dovecot/conf.d/10-master.conf
sudo sed -i "/#i7/a group = postfix" /etc/dovecot/conf.d/10-master.conf
sudo sed -i "/#i7/a mode = 0660" /etc/dovecot/conf.d/10-master.conf
sleep 1
echo ""
echo "Configure default to the standard ports, 143 for IMAP and 110 for POP3. With STARTTLS required for every connection"
echo ""
echo "sudo nano /etc/dovecot/conf.d/10-ssl.conf"
echo ""
sleep 1
sudo sed -i "s/#ssl_min_protocol = TLSv1/ssl_min_protocol = TLSv1/" /etc/dovecot/conf.d/10-ssl.conf
sudo sed -i "s/ssl = yes/ssl = required/" /etc/dovecot/conf.d/10-ssl.conf
# or if thats not there do this
sudo sed -i "s/#ssl = required/ssl = required/" /etc/dovecot/conf.d/10-ssl.conf
sudo sed -i "s/ssl_cert = <\/etc\/dovecot\/private\/dovecot.pem/ssl_cert = <\/etc\/letsencrypt\/live\/mail.$mailDomain\/fullchain.pem/" /etc/dovecot/conf.d/10-ssl.conf
sudo sed -i "s/ssl_key = <\/etc\/dovecot\/private\/dovecot.key/ssl_key = <\/etc\/letsencrypt\/live\/mail.$mailDomain\/privkey.pem/" /etc/dovecot/conf.d/10-ssl.conf
sleep 1
echo ""
sudo sed -i "s/mail_location = mbox:~\/mail:INBOX=\/var\/mail\/%u/mail_location = maildir:~\/Maildir/" /etc/dovecot/conf.d/10-mail.conf
echo "Check the Dovecot configuration"
echo ""
sleep 1
sudo dovecot -n
sleep 1
echo ""
echo "Restart dovecot"
echo ""
sudo systemctl restart dovecot
sudo systemctl restart postfix
sleep 1
echo ""
echo "Install mailutils"
echo ""
sudo apt install mailutils -y
sleep 1
echo ""
echo "Additional security options"
echo ""
echo "Skipping for now..."
echo ""
sleep 1
sudo systemctl restart postfix
echo "Everything should be set up, to test the mailserver"
echo ""
echo "Add this SPF record to your dns settings:"
echo "----------------------------------------------------"
echo "TYPE HOST ANSWER"
echo ""
echo "TXT @ v=spf1 ip4:$myIP -all"
echo "----------------------------------------------------"
read -p "Press enter to exit the script" xVar