5

I have set up smtp with gmail. When I use send_mail the from email is not showing up in the account receiving the email.

Django settings.py

# DEFAULT_FROM_EMAIL = 'sendTo@gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'sendTo@gmail.com'
EMAIL_HOST_PASSWORD = '**********'
EMAIL_USE_TLS = True

Using

$ python manage.py shell

I send the mail as follows,

>>> from django.core.mail import send_mail
>>> send_mail('subject is', 'message is and is not 12342', 'fromEmail@gmail.com', ['sendTo@gmail.com'])
1
>>>

I am receiving this email in my gmail account, (which is the same gmail account used for the smtp), but the from email is showing up as the sendTo@gmail.com and should be fromEmail@gmail.com

Shane G
  • 3,129
  • 10
  • 43
  • 85

2 Answers2

4

When you send emails through google's SMTP servers you cannot change the from email field. It uses the same address that you provided for authentication.

If you want to change it you have to use either your own mail server or one of the numerous mail apis/servers available. Sendgrid, MailGun etc come to mind.

e4c5
  • 52,766
  • 11
  • 101
  • 134
  • So this setup is no use for a contact form on a site as I will never know who the email is from. Is that correct? – Shane G May 19 '16 at 08:31
  • yes, because that's not one of the intended uses of the gmail smtp server. It's there solely for people to be able to send emails from third party email clients like thunderbird and non android phones. Not intended to be used for web sites. For that you need to get google apps services. – e4c5 May 19 '16 at 08:32
  • A solution to display the sender email is to add. headers = {'Reply-To': contact_email } in the sendmail option. – Yoann_R Sep 14 '16 at 19:33
  • My bad it is using the EmailMessage class: `headers = {'Reply-To': contact_email }`. See doc on emailmessage: [link](https://docs.djangoproject.com/en/1.10/topics/email/) – Yoann_R Sep 14 '16 at 19:54
3

I solved the problem using this view:

def contact(request):
    form = ContactForm(data=request.POST or None)

    if form.is_valid(): 
        subject = form.cleaned_data['sujet']
        message = form.cleaned_data['message']
        sender = form.cleaned_data['envoyeur']

        msg_mail = str(message) + " " + str(sender)

        send_mail(sujet, msg_mail, sender, ['corbin.julien@gmail.com'], fail_silently=False)

    return render(request, 'blog/contact.html', locals())

I actually append the email of the sender to the message. You could even remove the sender argument from send_mail. You just have to make your EmailField mandatory to make sure you'll get the sender's email address.

Uj Corb
  • 1,959
  • 4
  • 29
  • 56