aze
aze

Reputation: 850

Django mail send_mail uses host IP instead of hostname returned by getfqdn

According to the documentation, django default backend uses smtplib.

I am using django email to send emails in the following manner:

email = EmailMessage(
    'Object',
    'body',
    my_from_addr,
    args.emails,
    [],
    reply_to=['my_from_addr'],
)

with the following configuration in settings.py :

EMAIL_HOST = "mail_server.lan"
EMAIL_PORT = 25

I need to set the helo/ehlo parameter to comply with the email server according to the sending server hostname. But django seems to be using the IP of the server instead of the hostname, until now my emails have been rejected with the error

smtplib.SMTPRecipientsRefused: {'args.emails': (450, b'4.7.1 Client host rejected: cannot find your hostname, [192.168.1.5]')}

The smtplib documentation declares here

If specified, local_hostname is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found using socket.getfqdn().

And this actually returns the proper hostname:

python3 -c 'import socket; print(socket.getfqdn())'
my_proper_hostname.lan

Am I missing something? Why is django using the IP address instead of the real hostname?

Upvotes: 4

Views: 1215

Answers (2)

Oleg Russkin
Oleg Russkin

Reputation: 4404

This seems to be misconfiguration on mail server mail_server.lan. not in django.

SMTPRecipientsRefused error indicates errors encountered while sending emails to recipients - and this operation is performed by smtp mail server.

It received message from django (as there are no connection errors) and tried to send individual email for each recipient (to / cc) of that message. And sending one of them failed.

Mail server makes similar helo / ehlo negotiation with upstream servers.

Does your mail server provides correct maildomain / hostname ? (ip in error message suggests that mail server is sending ip, not its domain).

Then, many servers will also check PTR record for your ip - first, resolve provided mail domain name to get ip, then resolve this ip back - to get PTR record - to check that it matches mail domain. PTR record usually can be set with your internet provider / hoster.

Upvotes: 0

Toni Sredanović
Toni Sredanović

Reputation: 2412

You need to specify the host in your settings.py file:

For example:

EMAIL_HOST = 'email-smtp.eu-west-1.amazonaws.com' # specify email server address here

Upvotes: 1

Related Questions