DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
FREEDOM251

Freedom251 › Blog › Dovecot

How to Set Up a Mail Server With Postfix, Dovecot, MySQL and SpamAssassin

By Freedom251 Team · · 12 min read

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A reliable self-hosted mail system uses each component for a distinct job: Postfix handles SMTP connections and policy, MySQL stores virtual domains and mailbox metadata, Dovecot authenticates users and serves IMAP, Dovecot LMTP performs final delivery, and SpamAssassin scores messages before they reach a mailbox. Build and test those boundaries in that order. Do not enable SMTP authentication or accept internet mail until DNS, TLS, relay restrictions, database lookups and mailbox delivery all work independently.

What the finished system looks like

The design separates edge policy from mailbox access and storage:

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Incoming SMTP: Postfix accepts mail for domains it is authoritative for, applies recipient and relay policy, and hands accepted mail to Dovecot LMTP.
  • Authenticated submission: A dedicated Postfix service listens on port 587, requires STARTTLS, and sends authentication requests to Dovecot’s SASL UNIX socket.
  • Authentication and mailbox data: Dovecot reads password hashes and mailbox locations from MySQL through SQL-backed passdb and userdb queries.
  • Final delivery: Dovecot LMTP places messages in the correct virtual mailbox and can enforce Dovecot-side quota and mailbox rules.
  • Spam filtering: SpamAssassin’s spamd daemon receives messages through spamc or an MTA/content-filter integration, adds X-Spam-* headers, and then the message continues to delivery or Sieve processing.
  • Directory lookups: Postfix SQL maps query MySQL for virtual domains, mailbox recipients, aliases and optional access-control data.

This arrangement lets Postfix remain the SMTP policy engine while Dovecot owns authentication and mailbox placement. It also avoids duplicating mailbox-format and quota logic in Postfix.

Decide the deployment details before installing packages

Package names, service units and default configuration paths vary by operating system. Record these values first and substitute them consistently in every configuration file:

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
  • Operating-system release and the exact Postfix, Dovecot, MySQL and SpamAssassin package versions.
  • The fully qualified mail hostname, such as mail.example.com, and every hosted domain.
  • Public IPv4 and IPv6 addresses, the network provider that controls reverse DNS, and the DNS provider used for the zones.
  • The certificate authority or certificate-management method, private-key location and renewal procedure.
  • The mailbox storage root and the backup destination, including how a restore will be tested.
  • The identity used by each service to read MySQL. Use separate, least-privilege accounts where your design permits it rather than sharing a broad database credential.

Keep a written map of names and paths. A mismatch between the email identity used at login, the SQL query’s lookup key and the mailbox path is one of the most common causes of apparently valid credentials leading to failed delivery.

Prepare DNS, host identity and reputation controls

Publish forward and mail-routing records

  1. Create an A record for the mail hostname and an AAAA record when the server has a stable, reachable IPv6 address.
  2. Create an MX record for each hosted domain that points to that mail hostname. The MX target itself must resolve through the address records.
  3. Arrange reverse DNS (PTR) for each sending address with the network provider. The reverse name should identify the mail host and should agree with the forward DNS identity used by the server.

Plan sender-authentication records

SPF, DKIM and DMARC are separate from Postfix, Dovecot, MySQL and SpamAssassin, but they strongly affect whether other systems trust your mail. Decide which systems may send for each domain, where DKIM signing will occur, and which DMARC reporting and enforcement policy you can support before inviting real users.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not treat a successful local SMTP transaction as proof of internet deliverability. Reputation, reverse DNS, authentication alignment, complaint handling and abuse response remain your responsibility when you use your own address space.

Install and secure MySQL for virtual mail data

Create the data model

Use separate tables (or equivalent views) for at least:

  • Virtual domains, keyed by the domain name.
  • Mailbox identities, including the complete email address, a password hash and the mailbox location or UID/GID data needed by Dovecot.
  • Aliases, mapping an alias address to one or more destination addresses.
  • Optional access-control data used by Postfix restrictions.

The exact column names are your choice; what matters is that the SQL queries used by Postfix and Dovecot return the fields those services expect. Normalize the login identity consistently, normally as the full lowercase email address. Decide how addresses are canonicalized before you create users, because changing case or stripping a domain in only one component creates hard-to-diagnose failures.

Limit database access

  1. Run the operating system’s MySQL hardening procedure and remove unused accounts and remote access paths.
  2. Create a database dedicated to mail metadata.
  3. Create a low-privilege account for the mail lookups. Grant only the SELECT (and any narrowly required privilege) on the required tables.
  4. Store the username and password in configuration files readable only by the service or root. Do not place secrets in world-readable SQL map files, shell history or ticket attachments.
  5. Test the account with a read-only query for a known domain and mailbox, then test an unknown value and confirm it returns no row.

Plan capacity as well as permissions. Postfix SQL maps can create many concurrent MySQL clients on a busy system; use Postfix’s proxying approach where appropriate or size the database connection limits deliberately rather than discovering saturation during a traffic spike.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Configure Postfix’s MySQL SQL maps

Map each lookup type separately

Create SQL map definitions for the lookups your deployment uses:

  • virtual_mailbox_domains verifies that a recipient domain is hosted locally.
  • virtual_mailbox_maps verifies mailbox recipients and returns the mailbox destination or path information required by your chosen virtual-delivery design.
  • virtual_alias_maps expands aliases to mailbox or external destinations.
  • Optional access maps implement narrowly scoped allow, deny or policy lookups.

Keep each query understandable and testable. A domain query should answer only whether the domain exists; a mailbox query should distinguish an existing mailbox from an alias; and an alias query should return every intended destination in the format Postfix expects. Use the same database server, database name and credential policy across files, but do not duplicate a query’s purpose across unrelated maps.

Apply relay and recipient policy

Configure Postfix to reject destinations it is not responsible for, including the reject_unauth_destination restriction in the appropriate SMTP recipient checks. The submission service on port 587 must have a separate policy that requires authentication and is not an unrestricted relay. Test an unauthenticated attempt to relay to an external domain and verify that it is rejected before accepting the message.

Reload Postfix only after syntax checks and after the SQL account has been tested. Keep a copy of the last known-good configuration so a failed reload can be reversed without guessing which file changed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Configure Dovecot’s MySQL authentication and user database

Separate passdb from userdb

Dovecot’s SQL configuration has two distinct jobs:

  • Passdb finds the password hash and validates credentials.
  • Userdb returns mailbox location and per-user attributes after authentication succeeds.

Set the SQL driver to MySQL and write queries that use the same normalized login identity used by Postfix. Return no row for an unknown user. If your password hashes include an algorithm prefix, preserve it exactly so Dovecot can select the appropriate verifier. Keep mailbox paths deterministic; the userdb result should point to the same storage root that your backup and quota plans cover.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Validate authentication before wiring SMTP

Use Dovecot’s doveadm auth test with a test account and an intentionally incorrect password. A successful test proves that Dovecot can reach MySQL and interpret the hash; it does not yet prove that Postfix can reach Dovecot’s socket or that the mailbox is writable. Check logs for SQL connection errors, query syntax errors and userdb fields that are missing or empty.

Connect Postfix submission to Dovecot SASL

  1. Enable Dovecot’s authentication service and create its UNIX socket inside the Postfix queue area, commonly represented by a relative path such as private/auth.
  2. Set socket ownership and permissions so the Postfix process can read and use the socket, while unrelated users cannot.
  3. Configure Postfix to use Dovecot SASL and the relative socket path rather than an accidentally duplicated absolute path.
  4. Define a distinct submission service on TCP port 587. Require authentication there and apply submission-specific restrictions instead of copying the public port-25 service wholesale.

The path, service names and permission syntax differ by distribution. Confirm the effective configuration with the package’s validation command and inspect the running socket before attempting a client login.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Deliver accepted mail through Dovecot LMTP

Configure Dovecot’s LMTP service and create its UNIX socket. Point Postfix’s virtual transport at that socket so accepted mail follows this path:

Postfix recipient acceptance → SpamAssassin stage (when enabled) → Dovecot LMTP socket → Dovecot virtual mailbox

LMTP keeps mailbox placement, namespace handling and Dovecot quota behavior in one component. Confirm that the socket is present, that Postfix can connect to it, and that the userdb query supplies a valid mailbox location. A successful SMTP 250 response before LMTP handoff does not guarantee that the message was written; inspect the final-delivery log entry and the message ID.

Enable TLS before advertising authenticated SMTP

Install certificates safely

Install a certificate covering the hostname clients use and protect the private key with restrictive ownership and permissions. Record the renewal command or timer and test renewal before the first certificate approaches expiry. Configure both Postfix and Dovecot to use the intended certificate and key; using a valid certificate in only one service still produces client warnings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Set the submission policy

Require STARTTLS on port 587 and advertise AUTH only after TLS is active. Plaintext credentials expose the password to anyone able to observe the connection; TLS protects both SMTP content and SASL authentication data. Keep public inbound SMTP policy separate: receiving server-to-server mail and accepting authenticated user submissions are different trust cases.

Test certificate name matching, protocol negotiation and authentication with an SMTP client after TLS is established. Do not call a configuration secure merely because a client can connect to port 587; verify that authentication fails when attempted before STARTTLS and that an unauthenticated submission cannot relay.

Add SpamAssassin without interrupting delivery

Run the filtering stage

Start spamd and route messages through spamc or the content-filter integration appropriate to your Postfix layout. Keep site-wide rules in local.cf. Add SQL-backed user preferences only when per-user policies are genuinely required; otherwise the extra database dependency adds failure modes without improving a uniform policy.

Interpret scores and headers

SpamAssassin adds headers including X-Spam-Status and X-Spam-Level. Its documented default behavior tags messages with a calculated score of 5.0 or higher as spam (SpamAssassin 4.0 documentation). A tag is not the same as deletion: decide whether to leave the message in the mailbox, route it through a Sieve rule, quarantine it, or reject it, and make that decision explicit before enabling automatic rejection.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep filtering failure-safe

Watch filter latency and the behavior when spamd is unavailable. Ensure Postfix’s timeout and failure policy cannot silently discard accepted mail. During rollout, inspect headers on known clean and test messages, confirm that delivery still reaches LMTP, and review false positives before raising the consequences of a high score.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Test every boundary in a controlled sequence

Use a dedicated test domain or accounts and record timestamps, log lines and message IDs. Do not describe the system as tested unless these checks actually pass in your environment.

  1. DNS: Query the MX, A/AAAA and reverse-DNS records from outside the server’s network. Confirm the MX target resolves and that the PTR identity is intentional.
  2. MySQL: Run read-only lookups for an existing domain, mailbox and alias, then repeat with unknown values. Confirm that unknown recipients return no match.
  3. Dovecot SQL: Run doveadm auth test for a valid and invalid password. Verify both passdb and userdb results.
  4. SASL socket: Confirm the Dovecot auth socket exists at the path Postfix uses and that its permissions allow the Postfix process but not unrelated users.
  5. TLS: Connect with an SMTP client, inspect the presented certificate and attempt AUTH only after STARTTLS. Confirm pre-TLS AUTH is unavailable.
  6. Submission: Authenticate on port 587 and send a message to a local mailbox and a permitted external test address. Separately attempt unauthenticated relay and confirm rejection.
  7. Inbound delivery: Send mail from an external system to a hosted mailbox. Follow the message ID through Postfix acceptance, the SpamAssassin stage and the Dovecot LMTP delivery log.
  8. IMAP: Log in with the same full email address and verify that the delivered message is visible in the expected mailbox.
  9. Spam headers: Send a clearly marked test message and inspect for X-Spam-Status and related headers. Check that your chosen Sieve or mailbox policy acts only as intended.
  10. Aliases and rejects: Test alias expansion, an unknown local recipient, malformed authentication and an external destination that the server must not relay to.

Operate the server after launch

Protect secrets and limit abuse

  • Use separate low-privilege database identities where practical for Postfix and Dovecot, and protect every SQL and TLS secret.
  • Keep reject_unauth_destination and authenticated-submission restrictions active; never solve a delivery problem by temporarily turning the host into an open relay.
  • Apply operating-system and mail-software updates through a repeatable change process.
  • Document abuse-report handling, account suspension and rate-limit procedures before users send bulk mail.

Monitor the failure signals

  • Queue depth and message age, which reveal blocked delivery or a remote outage.
  • Authentication failures and unusual submission volume, which can indicate password attacks or a compromised account.
  • MySQL connection saturation and slow queries.
  • Disk usage in mailbox and queue files, plus backup success and restore-test results.
  • SpamAssassin processing time and its availability.
  • Certificate expiry, DNS changes, reverse-DNS status and delivery reputation complaints.

Backups are not complete until a restore drill proves that database records, mailbox files, aliases and configuration secrets can be recovered together. Keep recovery documentation separate from the live server so a host failure does not remove the instructions needed to rebuild it.

Common symptoms and targeted fixes

Users can authenticate to IMAP but not SMTP submission

Check the port-587 service rather than the public SMTP service, confirm STARTTLS completed first, and verify that Postfix can access Dovecot’s private/auth socket. A correct Dovecot password does not overcome a wrong socket path or UNIX-socket permission.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Postfix accepts mail but no message appears in the mailbox

Follow the message ID after SMTP acceptance. Confirm the SpamAssassin process returned control, the LMTP socket exists and is writable by the Postfix process, and the userdb query returned the expected mailbox location. Inspect Dovecot’s LMTP log for quota or path errors.

Valid users are rejected as unknown recipients

Run the exact Postfix mailbox query with the recipient’s full address, including its domain. Check domain and mailbox tables separately, normalization rules and SQL permissions. An authentication passdb row alone does not make a recipient valid to Postfix.

Messages are relayed or rejected unexpectedly

Review the active restriction order and whether the connection is on port 25 or 587. Ensure local-domain and recipient maps identify only hosted domains, and verify that authenticated-submission policy is not accidentally applied to server-to-server traffic.

Spam filtering delays or breaks delivery

Inspect spamd health, filter latency and Postfix timeout behavior. Confirm that clean messages still receive a deterministic handoff to LMTP when the filter is unavailable, and avoid enabling automatic rejection solely from a score tag until false positives are understood.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Self-hosting versus managed mail

Running this stack gives you control over mailbox data, SQL-backed virtual domains, custom filtering and configuration. It also makes you responsible for IP reputation, DNS, TLS renewals, backups, restores, monitoring, abuse response, incident handling and software maintenance. A managed VPS or hosted-email service shifts much of that operational work to a provider, but reduces control over the underlying configuration and may limit custom SQL or filtering behavior.

Decision factor Self-hosted Postfix/Dovecot stack Managed mail service
Data and configuration control Direct control of the server, database schema, mailbox storage and filtering policy. Provider controls infrastructure and may restrict low-level configuration.
Deliverability You build and protect IP and domain reputation, reverse DNS and authentication alignment. Provider supplies established delivery infrastructure, subject to its policies.
Maintenance You patch software, renew certificates, monitor queues and manage abuse. Provider handles much of the platform maintenance, with support boundaries defined by its service.
Recovery You design backups and prove restores for SQL data, mailboxes and configuration. Backup and recovery are delegated to the provider’s terms and procedures.
Customization Supports custom SQL-backed domains, aliases and SpamAssassin/Sieve policy. Customization depends on the service’s exposed features.
Cost model Infrastructure, storage, administration and reputation work are your ongoing costs. Usually a recurring service charge that trades some control for operational support.

Choose self-hosting when you can operate DNS, TLS, backups, monitoring and abuse response continuously—not merely when you can install the packages. Choose managed mail when predictable delivery and reduced administration outweigh the need for server-level control.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

DovecotIMAPLinux administrationLMTPMail ServerMySQLPostfixSMTPSpamAssassin

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.