Django contact form: email not sending - django

I'm currently building a contact form for my website in Django.
The only problem is that the email is not being sent when the form is submitted.
This is the code:
settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "c******o#gmail.com"
EMAIL_HOST_PASSWORD = '****'
EMAIL_PORT = '587'
views.py:
sender_name = form.cleaned_data['nome_completo']
sender_email = form.cleaned_data['email']
message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['messaggio'])
send_mail('New Enquiry', message, sender_email, ['c******o#gmail.com'])
My thought:
Since I'm in a virtualenv, when I submit the form, the terminal displays that it was successfully submitted, and gets me back the code right, maybe the email is not sent because of that, or maybe because I'm using a gmail account? Thanks!

Since you are using an SMTP server, why not use the following backend:
django.core.mail.backends.smtp.EmailBackend
Also, if you are using Gmail, make sure of the following:
Two-Factor authentication is enabled on account
You are using an app password.
You can find these on the security tab on your google account page:
https://myaccount.google.com/security

So the issue is with EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
This outputs emails to your console for debugging instead of actually sending emails. (See https://docs.djangoproject.com/en/3.1/topics/email/#console-backend)
Don't set EMAIL_BACKEND to anything for production as it defaults to django.core.mail.backends.smtp.EmailBackend. Then your EMAIL_HOST settings will take effect and the email should be sent out.

Related

SMTPAuthenticationError when sending gmail

I am having this error: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials ij28-20020a170902ab5c00b00163efcd50bdsm1197936plb.94 - gsmtp') when I try to send a gmail in my registration app
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'repository0612#gmail.com'
EMAIL_HOST_PASSWORD = '****************'
EMAIL_PORT = 587
I read in some other related forums that you just have to turn on the less secure apps in your google account settings but google already disabled that particular setting. I also tried turning off the 2-way authentication and my EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are as the same as my email and password. What else should I do to solve this problem?
This feature is no longer supported as of May 30th, 2022. See https://support.google.com/accounts/answer/6010255?hl=en&visit_id=637896899107643254-869975220&p=less-secure-apps&rd=1#zippy=%2Cuse-an-app-password
https://stackoverflow.com/a/27515833/19312416
So for new users we wont be able to use less secure app due to a new update, but there is nothing to worry.
In gmail after you allow 2 step authendication you will get a feature named app passsword you can use this.
Go to app password > provide name > copy password.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER =
EMAIL_HOST_PASSWORD = "paste that password"
this will work!
i believe your problem with code, try my function, it works with gmail, without additional settings
import smtplib
from email.mime.text import MIMEText
def email_sender(to_email, theme, message):
sender = "example#gmail.com"
password = "mypassword"
body = message
# make up message
msg = MIMEText(body)
msg['Subject'] = theme
msg['From'] = sender
msg['To'] = ", ".join(to_email)
#sending
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()
session.login(sender, password)
send_it = session.sendmail(sender, to_email, msg.as_string())
session.quit()
Thanks for the help guys. It already works by using the generated app password in my google account instead of using my own created password in EMAIL_HOST_PASSWORD

Django is not sending email to admins on error 500 (but email settings do work with send_mail!)

I know, there are plenty of similar questions about this, but none of them helped. When I set the EMAIL_BACKEND to django.core.mail.backends.console.EmailBackend, I do see the email when I trigger a 500. When I set EMAIL_BACKEND to django.core.mail.backends.smtp.EmailBackend, I don't receive the email.. but email manually sent using the send_mail function gets delivered just fine, so the email settings do work. I just don't understand this.
DEBUG = False
EMAIL_BACKEND = env("EMAIL_BACKEND")
EMAIL_HOST = "smtp.sendgrid.net"
EMAIL_HOST_USER = "apikey"
EMAIL_HOST_PASSWORD = env("SENDGRID_API_KEY")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
SERVER_EMAIL = "{my email}"
ADMINS = [
("Kevin Renskers", "{my email}"),
]
MANAGERS = ADMINS
I don't have any custom LOGGING set, and like I said with django.core.mail.backends.console.EmailBackend I do see the email in my console.
So how can it be that I can send email using send_mail, yet errors are not sent to me using the exact same email settings? I've looked in my sendgrid account activity, and yeah they are not sent at all.
Thank you #michjnich for the suggestion to try to call mail-admins manually. When I did I got a clear error:
The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved.
Turns out I needed to change SERVER_EMAIL to another email address as configured in Sendgrid. The reason why my manual send_mail call worked fine, is because I gave it the correct from address there.

Could not send email in django rest framework

I am developing password reset part of the project. I am using django_rest_passwordreset to get the password reset. I am using mailjet smtp. I could not send the email to the user.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'in-v3.mailjet.com'
# EMAIL_PORT = 465
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# EMAIL_USE_SSL = True
EMAIL_HOST_USER = '5e4329460b3c88f1d24d19c3e7374548aa213da%asasd1asd'
EMAIL_HOST_PASSWORD = 'a6c5ab2515d6ae761253a396453530ba$42asasdasdaasdasd'
If I change the EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' to the EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' it is printing it to the console. I have no idea why it is not working.
the part of the code where I am trying to send an email.
#receiver(reset_password_token_created)
def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs):
# send an e-mail to the user
context = {
'current_user': reset_password_token.user,
'username': reset_password_token.user.firstname,
'email': reset_password_token.user.email,
'reset_password_url': "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key)
}
# just checking if it works
send_mail('Hello from something', 'hello there', 'abdukhashimov#yandex.ru',
[reset_password_token.user.email, ], fail_silently=False)
# render email text
email_html_message = render_to_string('user_reset_password.html', context)
email_plaintext_message = render_to_string(
'user_reset_password.txt', context)
msg = EmailMultiAlternatives(
# title:
"Password Reset for {title}".format(title="Some website title"),
# message:
email_plaintext_message,
# from:
"noreply#somehost.local",
# to:
[reset_password_token.user.email]
)
msg.attach_alternative(email_html_message, "text/html")
msg.send()
I came up with a different solution. I used the google smtp service. I have followed the steps from this kinsta.com - steps to setup up google smtp.
Step1: The very first thing you will need to do is ensure that you have 2-step verification enabled on your primary Gmail account. Important: If you don’t do this you will get an invalid password error further below when trying to authenticate your email address. So first go and enable 2-step verification.
Step2: Next, you will need to generate an App password. You then use the app password in place of your personal Gmail password further below. This is the only way this process will work.
Step3: Now back in Gmail, go to settings, and can click on “Accounts and Import.” Then click on “Add another email address you own.”. Basically to the gmail and sign in with your account and go to the settings.
Step4: Enter your additional business name and business email that is on the custom domain.
(Extra Info). I usually use yandex mail and added it then it generated the followings.
Step5: It will then send an email confirmation code to the email you just added. You will need to click the link in the email to confirm it or manually enter the code (this proves that you are in fact the owner of the additional email account). And that’s it!
From my experience, you might need to tweak some settings from google if it did not work for you. For example, I read from other source, you might need to allow less secure apps from google. I have not done it as I was using yandex mail, I guess.
In case if you are not sure what to put in settings.py
EMAIL_HOST = 'smtp.yandex.ru' # in my case
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'added account'
EMAIL_HOST_PASSWORD = 'your password'
Credits to kinsta.com

Why does email be sent locally and not through server?

I'm working on a Django application.
I have set up all my required password reset views and corresponding pages.
In the final step I want to use Send Grid in my application to send the emails. I have the following setting s in my base.py file
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST_USER = 'codesniper99' # email id
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_PORT = 587
EMAIL_HOST_PASSWORD = '****' #password
EMAIL_USE_TLS = True
where **** is my password for the username codesniper99 on sendgrid.com
But when I use the password reset function I get locally generated email to my account. Like when i put email for reset as akhilvaid21#gmail.com
I get this:
when I push my code to my production server and not local host then it doesn't work and no email is sent. What am I doing wrong?
Also how do I change the name of webmaster#localhost???
Make sure you have set DEFAULT_FROM_EMAIL and SERVER_EMAIL in your settings.
Many email providers will only let you send email from verified email addresses. It looks as if Sendgrid might be blocking emails because Django is using the default webmaster#localhost for DEFAULT_FROM_EMAIL.

How can I change email sender's name in django

I'm creating email system in my django project and faced to next question:
Send email from custom email sender name, f.e. sending email from gmail(btw it works in my project) requires sending messages only from gmail account, same thing with smtp-pulse, sendgrid and etc. .
My question is: May I use any of already configured smtp servers in my case, or I only need to create my own using smtplib(f.e) and configure it?
Tried:
DEFAULT_FROM_EMAIL = 'support#site.com'
SERVER_EMAIL = 'support#site.com'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 2525
EMAIL_USE_TLS = False
EMAIL_HOST_USER = 'user#gmail.com'
EMAIL_HOST_PASSWORD = 'password'
This one doesn't work.
Same with mail.ru/smtp-pulse.com
Try
DEFAULT_FROM_EMAIL = "Site Support <support#site.com>"