I am trying to make EMAIL_HOST settings configurable within admin and I will create a model with required fields like:
- EMAIL_HOST
- EMAIL_HOST_USER
- EMAIL_HOST_PASSWORD
- EMAIL_PORT
But how can I use those fields in views using send_mail?
If you want to use send_mail
, you'll have to create your own email backend which uses your custom settings and then pass it to send_mail
in the connection
attribute.
This works for me
from django.core.mail import EmailMessage
from django.core.mail.backends.smtp import EmailBackend
config = Configuration.objects.get(**lookup_kwargs)
try:
backend = EmailBackend(
host=config.host,
port=config.port,
password=config.password,
username=config.username,
use_tls=config.use_tls,
fail_silently=config.fail_silently
)
mail = EmailMessage(
subject="subject",
body="body",
from_email=config.username,
to=["[email protected]"],
connection=backend,
)
mail.send()
except Exception as err:
print(err)
Sending mail with a custom configured SMTP setting in the admin page which is independent of the Django setting:
from django.core import mail
from django.core.mail.backends.smtp import EmailBackend
from <'Your SMTP setting in admin'> import <'Your model'>
def send_mail(subject, contact_list, body):
try:
con = mail.get_connection()
con.open()
print('Django connected to the SMTP server')
mail_setting = <'Your model'>.objects.last()
host = mail_setting.host
host_user = mail_setting.host_user
host_pass = mail_setting.host_pass
host_port = mail_setting.host_port
mail_obj = EmailBackend(
host=host,
port=host_port,
password=host_pass,
username=host_user,
use_tls=True,
timeout=10)
msg = mail.EmailMessage(
subject=subject,
body=body,
from_email=host_user,
to=[contact_list],
connection=con)
mail_obj.send_messages([msg])
print('Message has been sent.')
mail_obj.close()
return True
except Exception as _error:
print('Error in sending mail >> {}'.format(_error))
return False