Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Email backend (keeps sending email from incorrect "sender")

Tags:

email

django

I have several instances in my project where I attempt to send an email within a Django view.

I want to be able to hardcode the email sender within the view. When I try to do so, though, it continues to send the emails from the default account specified in my settings file.

Here is an example:

        if testform.is_valid():
            beta=testform.save()
            subject="Hi Beta Tester"  
            sender="[email protected]"

            recipient=[testform.cleaned_data['email']]

            text=loader.get_template('registration/beta_email.txt')
            html=loader.get_template('registration/beta_email.html')

            site_name='mysite'
            d=Context({'site_name':site_name})
            text_content=text.render(d)
            html_content=html.render(d)
                #This sends two mail versions, plain text and html
            msg=EmailMultiAlternatives(subject, text_content, sender, recipient)
            msg.attach_alternative(html_content, "text/html")
            msg.send()

            return HttpResponseRedirect('/splash/')

I thought that I could send specify the sender argument explicitly here. And, yet, when I test it, the email is being sent from the address listed in my settings file, configured as the following:

       EMAIL_USE_TLS=True

       EMAIL_HOST='smtp.gmail.com'

       EMAIL_HOST_USER='[email protected]'

       EMAIL_HOST_PASSWORD='private'

       DEFAULT_FROM_EMAIL='[email protected]'

Do I just have to remove the DEFAULT_FROM_EMAIL constant to make it work? I tried doing so and it seems to be working but I'm confused. In the Django documentation, it suggests that setting sender in the view should override the DEFAULT.

like image 953
Ben Avatar asked May 09 '11 19:05

Ben


2 Answers

I've finally figured out the issue here. Unfortunately, gmail rewrites the from and the envelope on authenticated smtp.

If you want to get around that, you have to use a third party mail server (which doesn't act like such a prissy) and then send mail to gmail users.

like image 114
Ben Avatar answered Sep 28 '22 08:09

Ben


For the sender e-mail try putting it in < > and you can add a name:

sender = "Formal Name <[email protected]>"

that is exactly the syntax I have in my e-mail sending view and it works.

There really shouldn't be a reason that adding the name to it would change how it's sending, but it may be worth trying and perhaps you want an easily readable name anyway.

like image 31
j_syk Avatar answered Sep 28 '22 07:09

j_syk