Soluções para problemas de email em uma nova instalação do Discourse

You just installed Discourse via the install guide, but email doesn’t seem to work. Unfortunately this means you can’t log in as an admin to finalize the install. :cry: Let’s troubleshootize!

Try the doctor :woman_health_worker:

If you run ./discourse-doctor it will check several ways that your mail configuration might be broken, and offer advice. Try that first.

Did you enter email settings correctly?

The simplest way is to run ./discourse-setup again. Did you enter everything correctly? But wait! If your password has anything other than numbers and letters, you might be better off editing your app.yml with nano or your favorite editor.

You can also double check the settings in your containers/app.yml file. A valid email section looks like this:

DISCOURSE_DEVELOPER_EMAILS: 'name@example.com'
DISCOURSE_SMTP_ADDRESS: smtp.mailgun.org
DISCOURSE_SMTP_PORT: 587
DISCOURSE_SMTP_USER_NAME: postmaster@discourse.example.com
DISCOURSE_SMTP_PASSWORD: aUd34cdWKCu6CTjfoH7ykk

Closely examine all values for correctness. Note that:

  • it all aligns
  • no leading # characters
  • single quotes around the developer email field
  • password does not include ", ', %, ] or other special characters

If you had any errors in your app.yml and made changes, you MUST rebuild the container for those changes to take effect!

cd /var/discourse/
./launcher rebuild app

Well, you don’t always need to rebuild

Doing a rebuild will often fix things that seem broken, but it takes a while. There are times when a full rebuild is not necessary; the above is usually the best advice, but If you change just SMTP settings, you can do just this to apply them without doing a full rebuild:

cd /var/discourse
./launcher destroy app
./launcher start app

Are your SMTP connections being blocked?

To confirm that your server can indeed contact the email server, issue this command:

telnet smtp.mailgun.org 587

If you can’t connect this way, you’re almost certainly blocked. (And if you do get connected, the escape character for SMTP is ctrl+], then use quit to exit telnet.)

If this happens, first try port 2525, and if that fails, contact your cloud provider support and confirm that your email connections are not being blocked.

What do the Discourse logs say?

From the command line, issue this command:

cd /var/discourse
tail shared/standalone/log/rails/production.log

This will show the last few lines of the log. Look for anything mail related. If you need to view the fuller logs, try

less shared/standalone/log/rails/production.log

To page through the complete log, press space or type GG to jump to the end. Look closely for any email related messages or press /, type email, and hit enter to search.

What do your email provider logs say?

Assuming there are no errors in the Discourse logs, or your Discourse mail configuration, the emails probably went out. The question, is what did your email provider do with them?

Most email providers have a log viewing function. Check the logs for your email domain and see what happened with the incoming emails.

Did you properly set up DKIM and SPF records for your domain?

You must enter those crucial DNS records for DKIM and SPF, otherwise your emails may arrive only sporadically, if at all.

Is the email domain correct?

The default email from address is based on the install domain plus subdomain, so if your URL is discourse.example.com it will be:

noreply@discourse.example.com

But if your mail provider is expecting:

noreply@example.com

… you may have problems! To get around this, edit and uncomment this exec line in app.yml

## If you want to set the 'From' email address for your first registration, uncomment and change:
#- exec: rails r "SiteSetting.notification_email='noreply@example.com'"
## After getting the first signup email, re-comment the line. It only needs to run once.

You’ll need to issue a rebuild after uncommenting the above line and setting the from email address as required.

You can also change this from the command line, if needed:

./launcher enter app
rails r "SiteSetting.notification_email = 'discourse@yoursite.com'"
exit

If using Mailgun – have you activated your domain and provided credit card info?

If you are using Mailgun, after you enter your DKIM and SPF records, you must visit https://mailgun.com/app/domains/YOUR.DISCOURSE.DOMAIN.com and click the “Check DNS Records Now” button. At the top of that page you should see “State ACTIVE” (in a calming green). If it says “State Unverified” (in a scary warning-yellow) Mailgun will not accept mail.

Mailgun now requires a credit card in order to deliver mail (other than to you). If your mailgun logs have a message about “free accounts,” this is your problem.

Other mail services have similar requirements.

Are you using an IP address as the mail domain?

This does not work in our experience. You must use a domain name when sending email, not an IP address like 192.168.1.1.

If you really want to go on with an IP address, try mail settings similar to these:

DISCOURSE_SMTP_ADDRESS: 172.17.0.1         # e.g. use internal docker IP here
DISCOURSE_SMTP_PORT: 587
DISCOURSE_SMTP_USER_NAME: "YOUR-SMTP-USER-NAME"
DISCOURSE_SMTP_PASSWORD: "YOUR-SMTP-PASSWORD"
DISCOURSE_SMTP_ENABLE_START_TLS: true     # (optional, default true)
DISCOURSE_SMTP_OPENSSL_VERIFY_MODE: none
DISCOURSE_SMTP_DOMAIN: example.com

Need to log in without receiving a registration email?

We don’t recommend this, because your email is still broken, and you have a broken Discourse until email is working. But if you absolutely must log in as admin with email broken, here’s what to do:

cd /var/discourse
./launcher enter app
rake admin:create

And answer the prompts. It takes a few seconds before they appear. When it asks for the password, you will not be able to see what you type. That is why it makes you type it twice.

Email smtp port selection (Using 465?)

The ability to be able to AUTH using ‘telnet’ is extremely important in your first steps of email troubleshooting.

Port 465 (SMTP over SSL) is largely deprecated in favor of STARTTLS on 25. You may need to try alternate ports such as port 2525 or port 587 (Mail Submission) when things do not seem to work as expected.

Command Line SMTP tests for experienced sysadmins

If you’re comfortable with the command line, these might help diagnose network or certificate problems. If these do not seem “easy-to-follow” then you should please ignore this section.

See also Test SMTP Authentication and StartTLS - Sysadmins of the North.

Office 365 Tweaks

If you’re using Office 365, be sure to include these (the first line is what you are likely missing):

DISCOURSE_SMTP_AUTHENTICATION: login
DISCOURSE_SMTP_ENABLE_START_TLS: true
DISCOURSE_SMTP_PORT: 587

and set the correct value for DISCOURSE_SMTP_NOTIFICATION_EMAIL (which is likely different from your forum hostname).

TLS and SSL issues

By default, Discourse uses STARTTLS to encrypt its connection to the email server. Some email servers (increasingly rare nowadays) don’t support this or aren’t configured to use it, so it can be disabled by adding this line:

DISCOURSE_SMTP_ENABLE_START_TLS: false    #default: true

Other email servers might support STARTTLS, but use a self-signed certificate. This is uncommon and can be enabled with:

DISCOURSE_SMTP_OPENSSL_VERIFY_MODE: none #default: peer

Email still doesn’t work! What next?

Anything else I forgot here? Feel free to edit this.


Debug issues with first connection to smtp server from inside the Discourse container

1. Enter your container:

./launcher enter app

2. Check dns resolving for your smtp server name via getent hosts:

(dig, nslookup, ping etc. are not installed inside the container.)

getent hosts your.smtp.server

On success, it will look like this or will be blank on failure.

# IPv4
123.123.123.123 your.smtp.server

# IPv6
2001:db8:0:0:0:ff00:42:8329 your.smtp.server

3. Try to open a connection to your smtp server via openssl:

(telnet, nc etc. are not installed inside the container.)

Fiddle with some different settings until you succeed with a connection.

openssl s_client -connect your.smtp.server:465
openssl s_client -connect your.smtp.server:587 -starttls smtp

# IPv4
openssl s_client -connect 172.17.0.123:465
openssl s_client -connect 172.17.0.123:587 -starttls smtp

# IPv6
openssl s_client -6 -connect "[2001:db8:0:0:0:ff00:42:8329]:465"
openssl s_client -6 -connect "[2001:db8:0:0:0:ff00:42:8329]:587" -starttls smtp

See: How to check SMTP connection → Step 3: Checking SMTP Connection Over TLS Using Openssl

4. Use your found working connection settings with Discourse.

:rocket:

Bonus: show Discourse IP from inside docker container

( ifconfig , ip etc. are not installed inside the container.)

hostname -I

Result like:

172.17.0.2

Last edited by @grayphilo 2025-03-04T18:51:41Z

Check documentPerform check on document:
57 curtidas

Esta informação está atualizada? Não funcionou para mim; tive que reconstruir o aplicativo após alterar a porta SMTP.

2 curtidas

Se discourse-doctor informar que a conexão com a porta 587 falhou, mas o comando openssl s_client -connect seu.servidor.smtp:587 -starttls smtp funcionar corretamente, tente o seguinte, ambos os comandos devem levar a mesma quantidade de tempo:

time openssl s_client -starttls smtp -connect seu.servidor.smtp:587 </dev/null > /dev/null

docker run --rm discourse/base:2.0.20231023-1945 bash -c 'time openssl s_client -starttls smtp -connect seu.servidor.smtp:587 </dev/null' > /dev/null

Se a versão do Docker for muito mais longa, você pode ter uma configuração incorreta em seu arquivo /etc/docker/daemon.json. Você pode tentar colocar o nameserver do Google em primeiro lugar:

{
  "dns": ["8.8.8.8", "ww.xx.yy.zz", "ww.xx.yy.za"]
}

A porta 2525 funciona para o Mailjet.
A porta 587 falhou.

2 curtidas

Eu editei o OP para sugerir o uso da porta 2525. É o seu serviço de hospedagem que bloqueia a porta. Por causa disso, muitos serviços de e-mail também suportam 2525.

3 curtidas

ei, só queria adicionar uma nota sobre isso;

O Mailgun agora exige um cartão de crédito para entregar e-mails (além de para você). Se seus logs do Mailgun tiverem uma mensagem sobre “contas gratuitas”, este é o seu problema.

Eu me inscrevi esta semana (julho de 2024) e, até agora, está funcionando sem a necessidade de adicionar um cartão de crédito, usando o nível gratuito básico. Com base no que vi em antigos tópicos de fóruns, parece que eles têm mudado de ideia sobre essa política e o uso e as limitações de seus níveis gratuitos, talvez

1 curtida

Uau. Isso é loucura e muito diferente de como as coisas têm sido por muito tempo.

Tem sido muito difícil para as pessoas descobrirem como mudar para o plano de pagamento conforme o uso e não se inscrever em um plano mensal bastante caro.

Você enviou para outros usuários além de si mesmo?

1 curtida

Sim, enviei para os usuários e está funcionando. O único problema é que, por algum motivo, os endereços de e-mail da AOL estão bloqueando meus e-mails, mas não acho que seja culpa do MailGun. Estou tão surpreso quanto você :slight_smile:

Atualização: parece que o motivo pelo qual alguns e-mails estão sendo bloqueados é porque o IP usado para enviar os e-mails gratuitos do MailGun é compartilhado, então ele foi relatado como “Spam” por algumas plataformas de e-mail como AOL, Yahoo Mail e outras. Parece que todos que não usam Gmail estão vendo e-mails devolvidos ou rejeitados.

1 curtida

Você pode me explicar como verificar as configurações em nosso arquivo containers/app.yml? Nós, novatos, não sabemos como fazer essas coisas sem instruções explícitas. lol

Se você não souber como usar uma ferramenta como o nano, execute o discourse-setup novamente. Depois que ele salvar as alterações, você pode pressionar control-c e então

./launcher destroy app;./launcher start app
1 curtida

ok, mas como verifico as configurações em meu arquivo containers/app.yml para que eu possa olhar a seção de e-mail e verificar se os dados estão corretos?

Se você não gostar da minha resposta, pode pesquisar por "nano" no Google.

Discutivelmente, o OP deveria dizer algo sobre nano, embora, como eu disse, se você não sabe o que é, basta executar o discourse-setup novamente, pois ele lê os valores no arquivo e você não pode estragar a formatação.

Ah, entendi o que você quer dizer agora. Quando você executa os comandos destroy e depois start, ele exibe os dados que eu preciso assim que é concluído. Minhas desculpas! :slight_smile:

1 curtida

Executei o doctor e recebi um erro que diz SMTPAuthenticationError. O doctor então diz que este não é um erro comum e que eles não têm sugestões sobre como corrigi-lo. Se isso acontecer, certifique-se de verificar novamente seu nome de usuário e senha SMTP, pois o processo de configuração do Discourse não informa se está errado, apenas não funciona (não envia e-mails) e deixa você sem saber o que fazer. Algumas coisas que fiz e que ajudaram foram acessar meu servidor via SSH usando Ubuntu em vez de LISH (porque estou usando Linode), porque LISH é terrivelmente instável e não suporta copiar/colar. Em seguida, refiz o processo de configuração e copiei e colei tudo desta vez em vez de digitar senhas de 100 caracteres, lol. De qualquer forma, espero que isso ajude alguns dos meus colegas novatos!

Seu nome de usuário ou senha está incorreto.

Não tenho certeza por que não consegui corrigir isso, mas o erro é bastante autoexplicativo.

Pode ser que você tenha copiado e colado errado. Pode ser que ele tenha caracteres que precisam ser escapados.

Utilizo o Brevo como meu remetente de e-mail de notificação, mas todas as notificações enviadas foram rejeitadas devido a um erro. Encontrei uma mensagem no Brevo afirmando que “O envio foi rejeitado porque o remetente que você usou não é válido. Valide seu remetente ou autentique seu domínio”. Por causa disso, meu fórum não pode funcionar. Estou pensando em como solucionar isso - que tipo de remetente eu preciso? Muito obrigado!!!

Para o endereço do remetente, pode ser definido como o subdomínio de e-mail que você está usando para enviar e-mails, como mail@domain_address.

Para autenticar o subdomínio + remetente, há algumas etapas para as quais eles têm um guia aqui:

Olá pessoal do Discourse!

Lutei por vários dias para configurar os parâmetros de e-mail com a porta 465, e a solução não está aqui nem em nenhum post que li no fórum (e eu realmente pesquisei).

Claro, é uma questão do que seu servidor de e-mail aceita. No meu caso, apenas 465 via TLS.

As duas linhas de configuração necessárias para adicionar em app.yml são:

DISCOURSE_SMTP_FORCE_TLS: true
DISCOURSE_SMTP_ENABLE_START_TLS: false
Alguns detalhes

As configurações padrão resultaram em um erro Net::ReadTimeout ao tentar um e-mail de teste com discourse-doctor. Enviar e-mails de teste de dentro do contêiner funciona bem com, por exemplo, curl, exatamente como neste post que me levou a metade da solução: Cannot send email - problem with port 465 - #10 by schungx

Só consegui descobrir a segunda configuração depois de olhar o conteúdo de app.yml e modificar este parâmetro. Tenho a sensação de que a maioria dos programas (por exemplo, Thunderbird) define implicitamente o protocolo correto ao selecionar a porta 465, então talvez o Discourse devesse? Isso parece ser realmente padrão, também como destacado aqui:

(link para o post completo)

Portanto, eu realmente defenderia a atualização da seção deste guia sobre a porta 465 ou fazer com que discourse-setup escolha automaticamente a melhor configuração.

2 curtidas

Normalmente eu não comento sobre as coisas, mas isso foi realmente útil!
Obrigado, o mantenedor do discourse deveria incluir essa configuração na configuração padrão, quero dizer, foi tedioso configurar o software deles, ainda assim não tenho nada a criticar, exceto que em um projeto tão grande algumas informações não estão disponíveis rapidamente e alguém deveria “mergulhar fundo”.
OK, funciona para mim!

Uma postagem foi mesclada em um tópico existente: Uso de % na senha SMTP para discourse-setup