Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmailBackend for sending email through multiple SMTP in Django

Tags:

email

django

smtp

Getting Django to send an email is nicely explained here using standard settings as shown below.

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "mail.mysmtpserver.somewhere" #EMAIL_PORT EMAIL_HOST_USER = "my@login" EMAIL_HOST_PASSWORD = "mypassword" #EMAIL_USE_TLS = True 

Then using django.core.mail.EmailMessage to send it of.

How ever, what if you are running multiple sites and need each of these to send email through their own SMTP server (or just different login in the same SMTP server)?

Searching for a EmailBackend like this or a way to do it with the current backend did not produce any satisfactory results.

like image 294
Tommy Strand Avatar asked Nov 27 '12 18:11

Tommy Strand


People also ask

How do I send an email to multiple recipients in Django?

How to send multiple mass emails django. We need to create a Tuple of messages and send them using send mass mail. In this tutorial, we create a project which sends email using Django. We fill the data in the form and send it using Django Email.

How do I send an email using Django?

In most cases, you can send email using django.core.mail.send_mail() . The subject , message , from_email and recipient_list parameters are required.

What is Django mailer?

django-mailer is a reusable Django app for queuing the sending of email. It works by storing email in the database for later sending.


1 Answers

If you want to override the provided settings you can just create your own connection and provide it to send_email or EmailMessage

from django.core.mail import get_connection, send_mail from django.core.mail.message import EmailMessage # TODO: Insert clever settings mechanism my_host = '' my_port = 587 my_username = '' my_password = '' my_use_tls = True connection = get_connection(host=my_host,                              port=my_port,                              username=my_username,                              password=my_password,                              use_tls=my_use_tls)   send_mail('diditwork?', 'test message', 'from_email', ['to'], connection=connection) # or EmailMessage('diditwork?', 'test message', 'from_email', ['to'], connection=connection).send(fail_silently=False) 

Update: Make sure to close the connection after use, @michel.iamit answer points to code showing the connection is cached for smpt. @dhackner answer shows how to automatically close a connection using with statement.

like image 187
Daniel Backman Avatar answered Nov 08 '22 21:11

Daniel Backman