djangodjango-formswagtailsmtplibwagtail-admin

Cannot set a sender email address in Django or Wagtail send_mail


The task: There is a website, offering a newsletter. I´m sending a newsletter subscription notification to an email address everytime a subscriber subscribes. For this I use send_mail from wagtail.admin.mail – I think it´s not relevant in which way I´m using send_mail.

The problem: I provide a from_email, but for some reason the email I receive contains the EMAIL_HOST_USER as sender – which is the email of the google mail account used for sending emails. I also tried from django.core.mail import send_mail but it´s the same. Is there any clue, how I can manage to make it work? Maybe they block to use custom email address showed as a sender?

Details: smtp.gmail.com and django.core.mail.backends.smtp.EmailBackend is used for the email backend.


Solution

  • Have a look at django.core.mail.message.EmailMessage

    You can explicitly set all the message properties in that class, including the connection and the from_email

    For connection, because I use different credentials across my site, I have a model to store connection settings and pull the relevant one for the job in hand.

    For instance, in my Contact form class, I have a property for the mail settings:

    @property
    def mail_settings(self):
        email_settings=EmailSettings.objects.filter(type='contact').first()
        if email_settings:
            use_ssl = getattr(email_settings, 'use_ssl')
            return {
                'host' : getattr(email_settings, 'host'),
                'port' : getattr(email_settings, 'port'),
                'username' : getattr(email_settings, 'username'),
                'password' : getattr(email_settings, 'password'),
                'ssl_setting' : use_ssl,          
                'tls_setting' : not use_ssl
            }
    

    then in the send_mail() method, I get the connection with django.core.mail.get_connection

        connection = mail.get_connection(**self.mail_settings)
    

    You can pass this connection into the EmailMessage constructor.