Configure direct-delivery incoming email for self-hosted sites

Discourse is all about enabling civilized discussion. While plenty of people like a web interface, e-mail is still the “hub” of many people’s online lives. That’s why sending e-mail is so important, and when you’re sending e-mail, you really want to be able to receive it, too. There are several reasons why:

  • If e-mails “bounce” (they can’t be delivered for some reason), you need to know about that. Repeatedly sending e-mails that bounce will get your e-mails flagged as spam. Receiving e-mail bounces allows you to disable sending to non-existent addresses.
  • Allowing people to reply to posts via e-mail can significantly improve engagement, as people can reply straight away from their mail client, even if they’re not able to visit the forum at that moment.
  • Letting people post new topics, or send PMs, via e-mail has similar benefits to engagement. In addition, you can use Discourse to handle e-mail for a group, such as an e-mail-based support channel (which is how Discourse’ own e-mail support is handled).

Delivering e-mail directly into your Discourse forum, rather than setting up POP3 polling, has a number of benefits:

  • No need to deal with gmail or another provider’s foibles;
  • You have more control over the e-mail addresses that people use to send posts; and
  • There are no delays in delivery – no more waiting for the next polling run to see new posts appear!

This howto is all about getting that hawtness into your forum.

Overview

This procedure creates a new container on your Discourse server, alongside the typical app container, which receives e-mail and forwards it into Discourse for processing. It supports all e-mail processes: handling bounces, replies, and new topic creation. Any self-hosted Discourse forum using our supported installation process can make use of this procedure to get easy, smooth-flowing incoming e-mail.

Container Setup

We’re going to get the mail-receiver container up and running on the server that’s already running your Discourse instance. There’s no need for a separate droplet just to handle mail – the whole container only takes about 5MB of memory!

So, start off by logging into your Discourse server, and becoming root via sudo:

ssh ubuntu@192.0.2.42
sudo -i

Now, go to your /var/discourse directory and create a new mail-receiver.yml container definition from the sample conveniently provided:

cd /var/discourse
git pull
cp samples/mail-receiver.yml containers/

Since every site is unique, open containers/mail-receiver.yml in your preferred text editor and change the MAIL_DOMAIN, DISCOURSE_MAIL_ENDPOINT, and DISCOURSE_API_KEY variables to suit your site. (If you are an advanced user and know that you are using nginx outside your container, see below for additional configuration for external nginx.)

:bulb: If you use the default mail endpoint (/admin/email/handle_mail), we suggest using the receive_email API key scope to provide an extra layer of security.

If you’re not sure what your favourite text editor is, try nano:

nano containers/mail-receiver.yml

Use Ctrl-X to exit (say “Yes” to “Do you want to save changes?”, or all your work will be for nothing).

Now, do an initial build of the container, and fire it up!

./launcher bootstrap mail-receiver
./launcher start mail-receiver

To check everything’s OK, take a peek in the logs:

./launcher logs mail-receiver

The last line printed should look rather a lot like this:

<22>Aug 31 04:14:31 postfix/master[1]: daemon started -- version 3.1.1, configuration /etc/postfix

If so, all is well, and you can go on to then next step.

DNS Setup

In order for everyone else on the Internet to know where to deliver mail, you must create an MX record for your forum. The exact details of how to do this vary by DNS provider, but in general, the procedure should be very similar to how you setup the DNS records for your forum in the first place, except that instead of creating an A (or “Address”) record, you’re creating an MX (or “Mail eXchange”) record. If your forum is at forum.example.com, and you set MAIL_DOMAIN to forum.example.com in the mail-receiver.yml, then the DNS record should look like this:

  • DNS Name: forum.example.com (this is the MAIL_DOMAIN)
  • Type: MX
  • Priority: 10
  • Value: forum.example.com (this is the domain of your forum)

To make sure the DNS is setup correctly, use a testing site such as http://mxtoolbox.com/ to look up the MAIL_DOMAIN you configured, and make sure it’s pointing to where you expect.

You can also now try sending an e-mail to nobody@forum.example.com. While Discourse won’t do anything useful with it yet, the e-mail you sent should show up in your admin panel under “Emails”, “Rejected” in a matter of seconds. If that happens, you’re definitely ready to proceed.

Note: outbound email providers like mailgun may ask you to add MX records pointing to their servers. You want to remove these so the MX records for your forum only point to your forum’s domain name. SPF and DKIM records must still point to your outbound email provider servers so you can send email.

Discourse Configuration

Now e-mail is being fed into Discourse, it’s time to explain to Discourse what to do with the e-mail it receives. For the most part, this is identical to setting up incoming e-mail via POP3 polling, with a few minor exceptions:

  • Enable the “manual polling” setting, rather than “pop3 polling”; and
  • You can automatically, without any further setup, use any address @forum.example.com as an address for category or group e-mails.

Troubleshooting

Nothing ever goes according to plan. Here’s how to figure out what went wrong.

  1. OCI runtime create failed error running ./launcher start mail-receiver? Your hostname might be too long. Rename it using these instructions and choose a shorter name, then rebuild.
  2. Did the e-mail even make it to mail-receiver? Run ./launcher logs mail-receiver, and look for log entries that mentions the address that the e-mail was sent from and to. If there’s none of those, then the message never even made it, and the problem is upstream. Check MX records, sending mail server logs, and firewall permissions (SMTP port 25).
  3. Is the message stuck in the queue? Run ./launcher enter mail-receiver, then run mailq. It should report, “Mail queue is empty”. If there’s any messages in there, you’ll get the to/from addresses listed. Messages only sit around in the queue if there’s a problem delivering to Discourse itself, so exit out of the container and then check…
  4. Did mail-receiver error out somehow? Run ./launcher logs mail-receiver | grep receive-mail and look for anything that looks like a stack trace, or basically anything other than “Recipient: <something>@forum.example.com”. Those error messages, whilst not necessarily self-explanatory, should go an awfully long way to explaining what went wrong. Look for typos in your yml file. In particular, check that DISCOURSE_MAIL_ENDPOINT URL matches your site URL, usually starting with https://.

Integrating with External nginx

If you are an advanced user and have configured external nginx such as for Add an offline page to display when Discourse is rebuilding or starting up you will find that the combination of mail-receiver and HTTPS being handled in external nginx requires slightly different handling to enable SSL for email over TLS. Here are example containers/mail-receiver.yml snippets that work with the recommended configuration for external nginx with letsencrypt certificates:

  POSTCONF_smtpd_tls_key_file:  /letsencrypt/live/=DOMAIN=/privkey.pem
  POSTCONF_smtpd_tls_cert_file:  /letsencrypt/live/=DOMAIN=/fullchain.pem

volumes:
  - volume:
      host: /var/discourse/shared/mail-receiver/postfix-spool
      guest: /var/spool/postfix
# uncomment to support TLS
  - volume:
      host: /etc/letsencrypt/
      guest: /letsencrypt

Note that you can’t export as a volume only /etc/letsencrypt/live because the actual files are symlinks into ../../archive/... and those won’t resolve if you are more specific in the volume specification.

Prevent outgoing host email from interfering (Postfix)

If you have (or want) automated messages from your host server (via Postfix), the mail-receiver will conflict because it needs port 25 to operate. One solution is to disable the host Postfix from listening on port 25:

nano /etc/postfix/master.cf

and comment out the line that looks like this:

smtp inet n - y - - smtpd

Then service postfix reload. You may also need to restart the mail-receiver container.

With both the host Postfix and the mail-receiver running, do netstat -tulpn | grep :25 to confirm that docker-proxy is using port 25.

Block unwanted domains from sending to you

To stop email from unwanted domains from even reaching your Discourse, your mail-receiver.yml should look something like this:

  DISCOURSE_API_USERNAME: system

  POSTCONF_smtpd_sender_restrictions: 'texthash:/etc/postfix/shared/sender_access'

volumes:
  - volume:
      host: /var/discourse/shared/mail-receiver/postfix-spool
      guest: /var/spool/postfix
  - volume:
      host: /var/discourse/shared/mail-receiver/etc
      guest: /etc/postfix/shared
# uncomment to support TLS
#  - volume:
#      host: /var/discourse/shared/standalone/letsencrypt
#      guest: /letsencrypt

Then create /var/discourse/shared/mail-receiver/etc path, and within it create a sender_access file containing the domains to reject, like this:

qq.com REJECT
163.com REJECT

Rebuild and you’re golden!

Further Reading

83 Likes
Set up reply by email with POP3 polling
Can Discourse ship frequent Docker images that do not need to be bootstrapped?
POP3 Authentication with CRAM-MD5
Set up reply by email with POP3 polling
Protonmail bridged SMTP in Discourse
E-mail polling on GMAIL not working
Whether it is possible to set the possibility of answering the noreply@mydomain.com adress?
Troubleshooting Gmail 'Poll via POP3 for email replies'
Does Discourse Need Incoming Mail?
Bad CSRF with mailgun replies
Reply via email failed
Set up reply by email with POP3 polling
Set up reply by email with POP3 polling
NOQUEUE: reject using Direct Email Delivery
Install Discourse on an isolated CentOS 7 server
Started getting 'Unknown To: Address" failures
Incoming e-mail not received
Set up reply by email with POP3 polling
Can I run wordpress in the same VPS with a second IP?
Getting 'address not found' error trying to set up reply via email
Trying to set up reply by email: ActionController::RoutingError (No route matches [POST] "/admin/email/handle_mail")
Joe's Personal Discourse Theme
Additional email address per user account support
How %{reply_key} create?
Allow inbound email delivery to forum contact email for inactive users
How %{reply_key} create?
Set up reply by email with POP3 polling
Code for receiving emails via Discourse API
Incoming e-mail not received
Incoming e-mail not received
Incoming e-mail not received
'hostname "mail.domain.tld" does not match the server certificate' :: SNI support? & how to query cert from Discourse container?
'hostname "mail.domain.tld" does not match the server certificate' :: SNI support? & how to query cert from Discourse container?
Will g-suite POP3 stop working on 2/15/2021
How to migrate from Yahoo groups to Discourse
Setting Up Mail
How to reset or recreate direct-delivery's mail-receiver container?
No received mails in new Discourse installation
Can I run wordpress in the same VPS with a second IP?
How might we better structure #howto?
Set up reply by email with POP3 polling
MKJ's Opinionated Discourse Deployment Configuration
Create new email address on forum domain
Emailed topics arrive only once per hour as opposed to instantly
Can I use SES for sending and Gsuite for receiving email?
Reply via email setup with Exchange 2016
Set up Microsoft Teams notifications using the discourse-chat-integration plugin
Disable reply via email?
How hard is it to handle Discourse after installation
(Can we?) Redirect all unrouted incoming emails to a category
Installation by the book
Learnings from setting up neighborhood community on Digital Ocean
Question about the email address domain used by Discourse
Configuring both direct delivery email and a forwarding rule
Configuring both direct delivery email and a forwarding rule
Able to receive e-mail in mail-receiver but NOT in Discourse?
Able to receive e-mail in mail-receiver but NOT in Discourse?
Email in main domain or sub-domain for the forum?
Mail receiver app
Self-hosted mail-receiver update following Let's Encrypt root certificate change
Discourse Mailgun Routes
Self hosted Reply by Email stopped working after latest update
AWS SES / AWS Lambda mail receiver endpoint code?
Mail questions and problems
Email forward ends up in original topic
Update mail-receiver to the release version
Customize direct-delivery Postfix configuration
Configure VERP to handle bouncing e-mails
Troubleshoot reply by email
Set up reply by email with POP3 polling
How to deactive account of those users who're not receiving emails
Filter known-bad sender domains from your mail-receiver
Need help with reply by email
Restore backup to a local instance in a safe/anonymized way
Custom domain email with discourse DO setup
Admin Interface and capabilities
Whether it is possible to set the possibility of answering the noreply@mydomain.com adress?
Generate LetsEnrypt certificates so mail-recevier can use them
Allow for email re-writing to solve the additional email address?
Webhook to forward posts to a mailinglist: best practice?
Email from Google: Review blocked sign-in attempt
"Discourse::NotFound" error when click "Email Type" field on admin/email/bounced
Looking for email hosting service recommendations
Creating a topic via email without write access to the category?
Bad CSRF with mailgun replies
Bad CSRF with mailgun replies
Use aliases in iRedMail for categories with incoming email feature enabled
[Paid] Discourse configuration changes
Allowing topic creation through direct delivery email in makes my forum vulnerable to spammers
Incoming e-mail not received
Failed to POST the e-mail (301 error)
Reply by Email, Gsuite, Limited users, Aliases?
Replying through email suddenly stopped due to Let's Encrypt changes
Can I start a new topic by sending an email message?

Hi, Thank you for your work to make direct-delivery so much easier!

When building the container, I get one error message that it can’t find ruby and one warning on locales
Full output:

/var/discourse$ sudo ./launcher bootstrap mail-receiver
x86_64 arch detected.
release: Pulling from discourse/mail-receiver
Digest: sha256:25abf0d6f1e4324fb0f6c6ec5839b20b6d6c685bb55eae63146065991ae5c9f4
Status: Image is up to date for discourse/mail-receiver:release
docker.io/discourse/mail-receiver:release
ERROR:  Can't find Ruby library file or shared library pups
cd /pups && /pups/bin/pups --stdin
/bin/bash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)
sha256:a97b69f89da4f9cb1441aca4f19c1cca8f717a54fdc75af54f4554f2c08da01e
516dc1c4fb59804256373f8a29aaf19d937e4d41b068dfa45d499c8d6b41aee5
Successfully bootstrapped, to startup use ./launcher start mail-receiver

Is this safe to ignore or a bug?
Using latest commit 8c40388ae4dabf1c0052ddd8eab4c72dbf7e0ca3 on branch main.

I suspect it’s OK. Start it up and see if it works.

1 Like

4 posts were split to a new topic: Incoming mail server has certificate error

I’ve 2 containers setup for my self-hosted website, nginx is setup outside the container.
And 3rd container for this mail setup is created now.
But, can you pls tell from where I can copy the above said variables of my site to be entered into new mail.yml?

You need a third container as descibed below this:

1 Like

Container is already created (it only needed one command). But then as described in above/initial post(s), I’ve to fill 2-3 values/variables in my mail.yml. I was in doubt from where do I copy the value for the same?

I think you’re asking how to find what values you should be setting those variables to. This is mostly explained in the comments around the variables in the file itself and besides the API key, probably you just need to replace discourse.example.com with your own forum’s domain name.

Here is the sample file in GitHub in case that makes it easier to read everything: discourse_docker/mail-receiver.yml at main · discourse/discourse_docker · GitHub

The API key comment directs you to the API section of your forum’s admin interface but it doesn’t talk about what kind should be created. Assuming you haven’t renamed your system user, it should look like this when creating the key: (enter your own description)

Then below that, find and tick receive emails:
image

After saving that, you will be given the API key needed for DISCOURSE_API_KEY.

4 Likes

My app.yml:

  ## Where e-mail to your forum should be sent.  In general, it's perfectly fine
  ## to use the same domain as the forum itself here.
  MAIL_DOMAIN: bathindahelper.com

# uncomment these (and the volume below!) to support TLS 
#  POSTCONF_smtpd_tls_key_file:  /letsencrypt/discourse.example.com/discourse.example.com.key
#  POSTCONF_smtpd_tls_cert_file:  /letsencrypt/discourse.example.com/fullchain.cer
#  POSTCONF_smtpd_tls_security_level: may


  ## The URL of the mail processing endpoint of your Discourse forum.
  ## This is simply your forum's base URL, with `/admin/email/handle_mail`
  ## appended.  Be careful if you're running a subfolder setup -- in that case,
  ## the URL needs to have the subfolder included!
  DISCOURSE_MAIL_ENDPOINT: 'https://bathindahelper.com/admin/email/handle_mail'

  ## The master API key of your Discourse forum.  You can get this from
  ## the "API" tab of your admin panel.
  DISCOURSE_API_KEY: abcdefghijklmnop

I changed 2 values: mail domain (doubt: don’t I prefix my domain name with some word, like ‘mail’ or only ‘m’)? And mail endpoint (doubt: would including only my actual domain name and leaving all the subfolder path up to ‘handle_mail’ as they’re in the sample file, would be ok?)
I am afraid that some more needs to be done here.

And then, I couldn’t find and copy my own site’s api keys (if I click on ‘All Api Keys’, there is only this one api key to be found). Giving screen shot:


And last, I’m in doubt that while setting my dns settings mx record here:
image

can I give 2 diff values to 'Dns Name and to ‘value’?
E.g.

Dns Name: bathindahelper.com
Value: mail.bathindahelper.com

This is one reason that you wanted your site to be at www.bathindahelper.com.

You appear to be using bathindahelper.com to receive mail already, so you need to do something now complicated.

Set the

You’ll need to configure the MAIL_DOMAIN in your mail_receiver.yml to mail.bathindahelper.com. Yes, you can have different values for the A record and the mx record. You already have two mx records for bathindahelper.com you don’t want to change those unless you don’t want to use that mailbox any more.

Add a dns A record for mail.bathindahelper.com with 5.161.135.164.

And an mx record for mail.bathindahelper.com pointing to mail.bathindahelper.com with priority 10.

Generate a new api key and paste it into the file.

./launcher rebuild mail_receiver.

I think that should do it, though it’s the middle of the night and I’m typing on my phone.

1 Like