Configure direct-delivery incoming email for self-hosted sites with Mail-Receiver

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_BASE_URL, 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_emails 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.

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.

  • Log into your Discourse forum as Admin and navigate to the Admin panel’s Site Settings, then click the Email tab. (forum.example.com/admin/site_settings/category/email)
  • Change the following settings:
    • Enable the reply by email setting
    • In the reply_by_email_address field, enter replies+%{reply_key}@forum.example.com
    • Enable the manual polling setting

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_BASE_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!

DMARC support

DMARC support has been enabled by default in the discourse/mail-receiver:release image to more strongly validate incoming email. This is enabled since the timestamped image discourse/mail-receiver:20240720054629.

This functionality can be toggled via the INCLUDE_DMARC docker environment variable. If a more permissive incoming mail server configuration is preferred, set that environment variable to false and rebuild the image.

The last version without DMARC support is discourse/mail-receiver:20211208001915.

Further Reading

Last edited by @kelv 2024-07-22T03:53:51Z

Check documentPerform check on document:
96 лайков
Can Discourse ship frequent Docker images that do not need to be bootstrapped?
Protonmail bridged SMTP in Discourse
E-mail polling on GMAIL not working
POP3 Authentication with CRAM-MD5
Whether it is possible to set the possibility of answering the noreply@mydomain.com adress?
Is there a way to use IMAP instead of POP3 for replies by email?
Does Discourse Need Incoming Mail?
Configure VERP to handle bouncing e-mails
How to migrate from Yahoo groups to Discourse
Bad CSRF with mailgun replies
Reply via email failed
Troubleshooting Gmail 'Poll via POP3 for email replies'
Setting Up Mail
Incoming e-mail not received
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?
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 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?
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?
Need help with reply by email
Reply Mailinglist
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
Configuring AWS SES for outgoing, bounce, and incoming email
Notes on Silencing or Deleting users
Self-hosted mail-receiver update following Let's Encrypt root certificate change
Use aliases in iRedMail for categories with incoming email feature enabled
Discourse Mailgun Routes
Reply-by email pop3 auth failure
Self hosted Reply by Email stopped working after latest update
Bounces not being received in Discourse with local Postfix server
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
User mentioned emails
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
Receiving emails into Discourse messages. Can this be done?
How to change the number of unicorns?
Trying to setup direct delivery of incoming email and new topic by email
Setting up a support inbox
Setting up a support inbox
When an existing staged user Joins my site, filled in user custom fields data isn't saved
Moving to Another VPS Provider
Enable receiving and reply emails
Enable receiving and reply emails
Late bounce messages when users reply to to direct messages via email
Want to set internal forum on our reactjs member's platform
Bottom line: Is Discourse now $12/month minimum on DigitalOcean? 😔 [Not yet! :slight_smile:]
Simple email inbox for discourse
Separate envelope-from and reply-to email addresses to avoid DMARC failure
Enable receiving and reply emails
What exact email address do I use for “Custom Incoming email address”?
Where do I put the variables for mail-receiver?
Install Discourse on an isolated CentOS 7 server
Discourse needs better search
Mailgun api key check backward (no API key should be required if bounces handled by mail receiver)
Mail-receiver won’t deliver mail to Discourse
Help understanding email setup
Mail Receiver setup
Does the mail-receiver work with arm?
How to configure Discourse to receive email from Mailgun?
Installing discourse for free?
Connection to the POP3 server is timing out
Can a single Mail Receiver handle emails for all sites in a Discourse multisite setup?
Mail-receiver relay access denied
Mail-receiver lacks an official ARM-compatible image
Mail-Receiver Configuration: 403 Error on smtp_should_reject Endpoint
Personal Message Replies Not Displaying in Inbox When Initiated via Auto-Quoted Post
Changing email SMTP From
Restore backup to a local instance in a safe/anonymized way
Enabling reply_by_email
📬 Repeated Postfix warnings and connections after valid_recipients implementation
Doc clarification: reply-key addresses in Cc (not just To) are processed
Introduction to development for notification mail sending with Gmail
Using "email in" feature for a Gmail account with AWS SES SMTP settings
Auto-restarting once a day via cron?
Email receive issue
Custom domain email with discourse DO setup
Where do I put the variables for mail-receiver?
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?
"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
[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?
NOQUEUE: reject using Direct Email Delivery
Started getting 'Unknown To: Address" failures
Can I run wordpress in the same VPS with a second IP?

7 сообщений были перенесены в новую тему: Работает ли почтовый получатель на ARM?

Похоже, этот контейнер кодирует email в параметр с именем email:

Судя по /logs, это устарело:

Уведомление об устаревании: предупреждение: параметр email устарел. Все POST-запросы к этому маршруту должны отправляться с параметром email_encoded, закодированным в строгом формате base64. Параметр email получен и помещен в очередь на обработку (удаление в Discourse 3.3.0)

Не могли бы вы обновить это перед удалением устаревшего параметра? :innocent:

6 лайков

Несколько заметок по настройке:

  • Обязательно защитите новый файл конфигурации контейнера командой: chmod o-rwx containers/mail-receiver.yml. Если этого не сделать, система предложит сделать это при запуске контейнера.
  • При создании ключа API я выбрал «Все пользователи» и область действия «Глобальная». Не знаю, сработает ли более ограниченный ключ.
  • В образце файла mail-receiver.yml настройки TLS сильно отличаются, поэтому лучше воспользоваться инструкциями здесь, а не пытаться редактировать образец.
  • В нём также есть настройка smtpd_tls_security_level, которую я раскомментировал. Я не проводил исследований, чтобы понять, нужна ли она или лучше использовать другое значение вместо «may».
  • Если вы хотите настроить электронную почту для конкретной категории, это можно сделать в /c/{category-name}/edit/settings. (Это полезно, если вы хотите создать что-то вроде категории для рассылки.) Для группы адрес электронной почты можно настроить в /g/{group-name}/manage/interaction.

Не знаю, поможет ли это кому-то ещё, но мне бы это пригодилось. :wink:

4 лайка

Вам действительно следует использовать ключ API с минимальными привилегиями. Эти настройки точно работают:

Уровень пользователя: Все пользователи
Область действия: Детальная
email—получение писем

5 лайков

Насколько я могу судить, моя настройка верна, но в Discourse нет записей ни об одном из писем.

Письма отображаются в логе следующим образом:

Mar 18 17:20:41 [myserver]-mail-receiver postfix/smtpd[122]: NOQUEUE: reject: RCPT from [XXX].google.com[XXX.XX.XXX.XXX]: 554 5.7.1 <test004@www.[mysite].com>: Recipient address rejected: Mail to this address is not accepted. Check the address and try to send again?; from=<[sender]@gmail.com> to=<test004@www.[mysite].com> proto=ESMTP helo=<[XXX].google.com>
Mar 18 17:20:42 [myserver]-mail-receiver postfix/smtpd[122]: disconnect from [XXX].google.com[XXX.XX.XXX.XXX] ehlo=2 starttls=1 mail=1 rcpt=0/1 bdat=0/1 quit=1 commands=5/7

Кроме того, на отправляющий адрес приходит уведомление об отказе. В очереди ничего не остаётся, а в логах нет никаких следов ошибок. Я трижды проверил, что все URL совпадают, и на странице настроек API видно, что ключ используется. Однако список отклонённых писем в панели администратора остаётся пустым.

Есть какие-нибудь предложения?

Ошибка указывает на то, что MAIL_DOMAIN не установлен в значение www.[mysite].com, либо нет категории или группы, настроенной для получения писем, отправленных на test004@www.[mysite].com.

1 лайк

Спасибо за ваш ответ. Я проверил MAIL_DOMAIN всеми возможными способами, перепробовал все комбинации значений MAIL_DOMAIN и целевых адресов электронной почты. С каким значением в настройках Discourse он сверяется? Например, DISCOURSE_HOSTNAME, DISCOURSE_SMTP_DOMAIN или что-то ещё?

Я немного запутался из-за вашего второго предложения, учитывая эту строку из оригинального сообщения:

Разве отклонения не должны отображаться ещё до того, как Discourse настроен для работы с ними? Ошибки доставки (bounces) тоже не появляются. Я протестировал это, используя метод, рекомендованный здесь: Настройка VERP для обработки возвратов писем. Никаких следов на странице /admin/email.

Есть ли в каком-либо из контейнеров лог, который показывает (или который можно настроить так, чтобы он показывал) больше информации о взаимодействии между mail-receiver и app?

1 лайк

Существует два основных типа отклонений: те, которые происходят на раннем этапе и решают, следует ли передавать письмо в EmailReceiver Discourse, и те, которые возникают в процессе обработки почты самим Discourse.

По моему опыту, первые не отображаются в логах Discourse, то есть большинство (если не все) отклонений, связанных с почтой (неудачная проверка DMARC, неверный адрес и т. д.), там не фиксируются. Те, что появляются, — это такие случаи, как слишком короткое письмо, пользователь не имеет права публиковать сообщения и т. д.

Не уверен, изменилось ли что-то с момента написания этого абзаца, но мой опыт за последние ~2,5 года, начиная с момента настройки, был именно таким.

Если я отправляю письмо на test-reject@[my-instance], я получаю общее уведомление об ошибке от своего почтового провайдера (не от mail-receiver / Discourse), сообщающее, что адрес получателя был отклонён. Это происходит потому, что mail-receiver отклоняет письмо во время SMTP-взаимодействия.

Уведомления об ошибках доставки и VERP относятся к письмам, которые ваш экземпляр Discourse отправляет, а не получает, например, для автоматической остановки отправки уведомлений на адрес, который постоянно возвращает ошибки доставки. Они не связаны с mail-receiver.


Мне кажется, что цитата из руководства ввела вас в заблуждение, и на самом деле всё, вероятно, работает правильно. Отправка на some-random-address@MAIL_DOMAIN не будет принята и не отобразится в отклонениях, поэтому это не очень полезный тест сам по себе (кроме проверки того, что mail-receiver получает письма, что вы уже подтвердили).

Перейдите в существующую категорию или создайте новую, откройте её конфигурацию и перейдите на вкладку настроек. Внизу вы найдёте параметр custom incoming email address (пользовательский адрес входящей почты). Установите его в значение something@MAIL_DOMAIN, например, тот же адрес test004, который вы пробовали ранее, сохраните изменения и попробуйте отправить письмо на этот адрес.

Это должно пройти проверку mail-receiver, после чего вы либо увидите новое сообщение в категории, либо отклонение в системе Discourse.

1 лайк

Спасибо, это очень полезное уточнение. Я настрою и протестирую, чтобы убедиться.

Что касается возвратов, то я снова запутался из-за автора оригинального поста, так как возвраты указаны в самом начале списка причин, по которым стоит следовать этому руководству.

Так что даже с такой настройкой и даже если я удалил MX-записи Mailgun, мне всё равно нужно настроить VERP на их стороне, чтобы перехватывать возвраты и прочее? Ну что ж, я думал, что прямая доставка — это обходной путь для моих проблем с вебхуками Mailgun, похоже, мне придётся снова заняться устранением неполадок.

2 лайка

О, извините, вы правы: там сказано, что вы можете использовать mail-receiver для отказов, но я не очень хорошо разбираюсь в том, как это работает.

Мой mail-receiver не получает отказы, но я использую вебхуки Mailgun. Возможно, Mailgun меняет отправителя в конверте, и поэтому отказы приходят, если вебхуки включены. (То есть, если бы вебхуки были отключены, возможно, мои отказы приходили бы в mail-receiver.)

1 лайк

Да, я почти уверен, что это сейчас неточно, поскольку fast-rejection был реализован в… (проверяю git log) мае 2017 года.

Без просмотра вашей реальной конфигурации, включая конфигурацию групп/категорий Discourse, очень трудно сказать, что именно идет не так. Хотя по крайней мере в 80% случаев это где-то опечатка; попросите коллегу (не обязательно глубоко технического специалиста) посмотреть на это, и он, скорее всего, заметит, где вы поставили l вместо i, примерно за пять секунд. Моя жена делает это для меня на регулярной основе.

Это так. При прямом доставке ваш провайдер исходящей почты вообще не должен участвовать в обработке входящей почты. Всё, будь то новая тема, ответ или отскок, должно идти прямо в mail-receiver (а оттуда в Discourse для обработки).

3 лайка

Я почти уверен, что со мной на прошлой неделе произошло именно это с такой же проблемой. В итоге я скопировал другой файл YML откуда-то ещё, и всё заработало.

Хотя это показалось странным, Мэтт. Я посмотрел в файлы postfix, и они тоже выглядели правильно, но система сообщала, что имя хоста не совпадает. Клянусь, я копировал и вставлял его, но, возможно, я совершил ошибку, подумав, что могу просто ввести его вручную.

1 лайк

Хорошо, что голосовое распознавание ИИ скоро исправит это за нас. :troll:

3 лайка

Вы были правы: настройка электронной почты для категории и отправка писем туда сработала как ожидалось. Я просто бился головой об стену, потому что отказы происходили молча.

Рад, что теперь я это знаю, и надеюсь, что руководство будет обновлено, хотя лично я бы предпочёл, чтобы всё работало так, как описано в руководстве. Например, если пользователи пытаются отправить письмо на какой-то адрес, и это не удаётся, это могло бы помочь мне либо уведомить их, либо понять, что есть спрос на общение с категорией или группой по электронной почте. Без такой возможности, похоже, нет простого способа увидеть эти письма.

Это всё ещё не работает как ожидалось. Я настроил вебхуки, поэтому могу видеть несколько отскоков, но я знаю, что они из вебхуков Mailgun, потому что в них описана проблема: ошибка “Discourse::NotFound” при нажатии на поле “Тип письма” на admin/email/bounced.

Я не совсем понимаю, как Mailgun вообще получает отскоки, поскольку у меня нет MX-записей, указывающих на их серверы. Предполагаю, что они устанавливают путь возврата при отправке исходящего письма?

Я вижу отскоки в логах mail-receiver, но они не попадают в app. Похоже, они молча отклоняются. Вот строка в логах, которую я могу связать с отскоком, полученным через вебхуки:

NOQUEUE: reject: RCPT from mail-[id1].outbound.protection.outlook.com[XX.XX.XX.XX]: 450 4.7.1 <bounce+[id2]-[email]=[address].com@www.[mydomain].com>: Recipient address rejected: Internal error, API request failed; from=<> to=<bounce+[id#]-[email]=[address].com@www.[mydomain].com> proto=ESMTP helo=<[id3].outbound.protection.outlook.com>

Нужно ли мне добавить bounce+{%something}@www.mydomain.com в качестве белого адреса где-нибудь, чтобы они проходили?

2 лайка

Да, скорее всего, они переписывают обратный путь (также известный как «envelope from»), когда исходящее письмо проходит через их серверы. Вероятно, где-то есть настройка, позволяющая отключить это, но я не работал с Mailgun, поэтому не могу сказать наверняка (или где именно находится такая настройка).

Хорошо, это ошибка между почтовым получателем и Discourse. В логах незадолго до этого должна появиться строка, начинающаяся с «Failed to GET smtp_should_reject answer», которая расскажет подробнее о том, что не удалось и почему. Это также должно соответствовать какому-либо сообщению об ошибке в логах Discourse.

2 лайка

Mar 21 17:02:21 discourse-smtp-fast-rejection[1149]: Не удалось получить ответ smtp_should_reject по адресу https://www.mydomain.com/admin/email/smtp_should_reject.json: 400

Может ли это быть связано с пустым отправителем, from=<>? В логах я ничего об этом не вижу. Означает ли код 400, что файл smtp_should_reject.json не существует?

2 лайка

Если бы этого HTTP-ресурса не существовало, это был бы ответ 404, а не 400. Я не думаю, что отправитель с null-значением должен вызывать проблему, поскольку именно так доставляются все уведомления о недоставке. Неверный ключ API, по-моему, должен возвращать ответ 403, но я не могу утверждать это со стопроцентной уверенностью, поэтому это, вероятно, стоит проверить на всякий случай. Если логи Discourse не дают никаких указаний на то, почему запрос оказался некорректным, боюсь, вам, скорее всего, предстоит мучительная отладка — у меня сейчас нет системы с включённой поддержкой mail-receiver, с которой я мог бы легко поэкспериментировать. Боюсь, чтобы докопаться до сути происходящего и исправить это для вас, мне пришлось бы выполнить эту работу как консультант.

3 лайка

На данный момент это, похоже, ни на что не влияет: отклики работают с вебхуками, и большинство откликов не генерируют письмо (в другой теме упоминался этот ответ на Stack Overflow, что совпадает с тем, что я наблюдаю). Функция «ответ по электронной почте» также работает как положено. Какая бы ошибка ни была, она редка и не нарушает нормальную работу.

Я буду следить за этим на всякий случай и сообщу, если узнаю что-то полезное для других. Ещё раз спасибо за помощь!

2 лайка

@JammyDodger Не могли бы вы переименовать это так, чтобы поиск по «mail-receiver» находил эту тему? С тех пор как три года назад из заголовка убрали слово «straightforward», мне почти не удавалось найти эту тему без нескольких попыток.

4 лайка