Send_mail in Django, works in shell, works locally

2019-04-29 06:50发布

问题:

I'm not even sure how to debug this: I'm using send_mail in one of my views in Django. It works fine when using the app locally (using the same SMTP settings I use in production), and it works fine from the shell in production (again, using the same settings). But when I actually use the app in production, the message doesn't send. Any idea how to troubleshoot?

I won't paste in the whole view, but here's the relevant section.

if request.method == 'POST':
    message, form = decideform(request.POST)
    if form.is_valid():
        invitation.status = form.cleaned_data['status']
        invitation.save()
        message, form = decideform(request.POST)
        update = 'Thank you for updating your status.'

        # Send an email confirming their change
        subject = 'Confirming your RSVP [%s %s]' % (invitation.user.first_name, invitation.user.last_name)
        body = message + ' Remember, the URL to update or change your RSVP is http://the.url%s.' % invitation.get_absolute_url()
        send_mail(subject, body, 'rsvp@mydomain.com', ['rsvp@mydomain.com', invitation.user.email], fail_silently=True)

And here's the relevant bits from my local_settings file, with salient details altered for security's sake:

EMAIL_HOST = 'mail.mydomain.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'rsvp@mydomain.com'
DEFAULT_FROM_USER = 'rsvp@mydomain.com'
EMAIL_HOST_PASSWORD = 'p4ssw0rd'

回答1:

Check permissions. It could be that you have permissions to run send_mail, but the app doesn't.



回答2:

I am having the same issue. 3 years after :) copying the code of send_mail inline fixed it but I still don't know why

        connection = django.core.mail.get_connection(username=None, password=None, fail_silently=False)
        mail = django.core.mail.message.EmailMessage('hello', 'world', 'test@gmail.com', ['test@gmail.com'],                                              connection=connection)
        mail.send()            


回答3:

You can try django-sendgrid instead which is very easy to configure.Use settings like this

EMAIL_BACKEND = "sgbackend.SendGridBackend"
SENDGRID_USER = 'xxxxxx'
SENDGRID_PASSWORD = 'xxxxxx'
EMAIL_PORT = 1025