Django email backend and smtp configuration - python

I'm trying to use my Zoho account within my django project, in order to receive emails via contact forms.
I also followed this guide: https://www.zoho.com/mail/help/zoho-smtp.html
In the 'settings.py' file I wrote:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtppro.zoho.eu'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '<domain name email>'
EMAIL_HOST_PASSWORD = '<password>'
and in views.py:
def home(request):
allTemplates = AllTemplates.objects.all()
if request.method == 'POST':
form = forms.ContactForm(request.POST)
if form.is_valid():
body = {
'name': form.cleaned_data['name'],
'surname': form.cleaned_data['surname'],
'from_email': form.cleaned_data['from_email'],
'message': form.cleaned_data['message'],
}
mail_body = "\n".join(body.values())
try:
send_mail("Generic contact", mail_body, '<domain name email>',
['<domain name email>'], fail_silently=False)
except BadHeaderError:
return HttpResponse('Ops, qualcosa è andato storto')
form = forms.ContactForm
context = {'form': form, 'allTemplates': allTemplates,
'allTemplates_length': len(allTemplates)}
return render(request, 'home.html', context)
N.B. in 'send_email' I entered my email address twice to test
I also tried to use ssl
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtppro.zoho.eu'
EMAIL_PORT = 465
EMAIL_USE_SSL = True
EMAIL_HOST_USER = '<domain name email>'
EMAIL_HOST_PASSWORD = '<password>'
but nothing, I don't receive any email.
Is there anyone who has already gone through it or who can direct me towards some document or guide to study?
Thank you very much in advance.

I use
EMAIL_PORT = 587
EMAIL_USE_TLS = True
my biggest pain was that all emails went to spam folder and I did not realize that for 2 hours.
test with local output to terminal:
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
test with local mail server to make sure the email is correctly created:
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST='localhost'
EMAIL_PORT=1025
and start local test mail server parallel to runserver in terminal window:
python -m smtpd -n -c DebuggingServer localhost:1025

Related

SMTPServerDisconnected even though it was working properly a few days ago

I am using Django and I'm trying to send a verification email (with gmail) when the user registers, this was working fine some days ago, but then it suddenly stopped working. I have already created a new Google Application password and it is still not working. When the site tries to send the email it raises "SMTPServerDisconnected at /register/Connection unexpectedly closed".
This are my settings for email.
# EMAIL CONFIG
DEFAULT_FROM_EMAIL = 'mymail#gmail.com'
EMAIL_FROM_USER= 'mymail#gmail.com'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'mymail#gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
And this is my view:
def send_action_email(user,request):
current_site = get_current_site(request)
email_subject = 'Activa tu cuenta'
email_body = render_to_string('users/activate.html',{
'user':user,
'domain':current_site,
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
'token': generate_token.make_token(user)
})
email = EmailMessage(subject=email_subject,body=email_body,
from_email=settings.EMAIL_FROM_USER,
to=[user.email]
)
email.send()
def activate_user(request,uidb64,token):
try:
uid=force_text(urlsafe_base64_decode(uidb64))
user= User.objects.get(pk=uid)
except Exception as e:
user=None
if user and generate_token.check_token(user,token):
user.email_is_verified=True
user.save()
messages.success(request, 'Se ha verificado tu email, ya puedes inciciar sesion!')
return redirect('login')
return render(request,'appName/activation_failed.html',{"user":user})
Might it be that google is not allowing me to login to the mail?

STARTTLS extension not supported by server in django

i am using gmail to do this, and i'm still at development. it just keeps throwing this error. yesterday it was working. sometimes it would also stop and show this error, but throughout today it haven't been working as expected
setting.py
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = "testemail#gmail.com"
EMAIL_HOST_PASSWORD = "mypassword"
views.py
def mail_letter(request):
emails = NewsLetter.objects.all()
df = read_frame(emails, fieldnames=['email'])
mail_list = df['email'].values.tolist()
print(mail_list)
if request.method == "POST":
form = MailMessageForm(request.POST)
if form.is_valid:
form.save()
# Sending Messages
title = form.cleaned_data.get('title')
message = form.cleaned_data.get('message')
send_mail(
title,
message,
'',
mail_list,
fail_silently=False,
)
# Success Alert
messages.success(request, f"Messages sent successfully")
subscribed = True
return redirect('elements:mail_letter')
else:
form = MailMessageForm()
This was later fixed by connecting to a new network, my network connection was not good

Using Django to send Gmail

This is very much potentially a duplicate question, but none of the other obvious duplicates have resolved the issue for me:
This is an inherited project.
My settings.py includes:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'my_username#gmail.com'
EMAIL_HOST_PASSWORD = 'my_password'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'my_username#gmail.com'
DEFAULT_FEEDBACK_EMAIL = 'my_username#gmail.com'
SERVER_EMAIL = 'my_username#gmail.com'
ACCOUNT_EMAIL_VERIFICATION = 'none'
The code that I'm trying to run is:
subject = 'Subject'
template = get_template('accounts/email-templates/email-activation.html').render(Context(ctx))
email = EmailMessage(subject, template, to=[send_to])
email.content_subtype = "html"
try:
email.send()
My error when trying repeatedly with python manage.py shell is:
gaierror: [Errno 8] nodename nor servname provided, or not known
My dns seems fine, sudo killall -HUP mDNSResponder and dscacheutil -flushcache have been run without success, but I'm hardly an expert on dns settings.
My hosts file is:
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
Advice appreciated!
You might need to generate an app password in Gmail or change the settings to allow less secure access. I don't think Gmail will allow you to just use your regular password in - what Google would consider - an insecure manner.
I had similar problem working with Gmail to send mails.
Try only the following codes to send emails. Hope it helps:
In settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "sender_email#gmail.com"
EMAIL_HOST_PASSWORD = "email_password"
EMAIL_PORT = 0
EMAIL_USE_TLS = True
Codes to send emails:
# Imports for sending emails:
from django.conf import settings
from django.core.mail import EmailMultiAlternatives, send_mail
emailFrom = [settings.EMAIL_HOST_USER]
emailTo = email_here
text_content = 'Your content here'
email_subject = "Subject here"
msg = EmailMultiAlternatives(email_subject, text_content, emailFrom, [emailTo], )
msg.send()
Also change the settings in the 'sender gmail account' to create a passage for the mail to be send from the sender to the receiver. Hope this helps.

Django Mailer not finding server

I'm trying to send an email through Django's wrapper.
Here are my relevant settings.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
The Email, which I am trying to isolate in the most basic form of a view:
from django.core.mail import send_mail
def index(request):
subject = 'Subject'
message = 'message'
from_email = settings.DEFAULT_FROM_EMAIL
send_mail(subject, message, from_email, ['email#example.com'])
return render(request, "index.html")
All of the emails and password are legitimate. When I execute the code, I get thrown an error message:
SMTPAuthenticationError at /....*Link to sign into my account*
Please log in via your web browser and\n5.7.14 then try again
I did that but continue to get the same message. The password I give in the app is correct. Is there anything I need to configure in my gmail account?
Change EMAIL_HOST = 'smtp.gmail.com ' toEMAIL_HOST = 'smtp.gmail.com' and I bet your problem will disappear :)
EDIT #1
You are running into authentication issues as EMAIL_USE_TLS is True and Gmail only requires TLS connections for SMTP on port 587. Change to EMAIL_PORT = 587 and you should bypass the issue.
EDIT #2
The error you see can be fixed through your Gmail settings. See -
Django SMTPAuthenticationError

Forgot password emails not sending in Django

I am trying to implement password reset functionality.
My urls contains:
url(r'^password_reset/$','django.contrib.auth.views.password_reset', {'template_name': 'resetpassword.html', 'post_reset_redirect' : '/password_reset/mailed/'},
name="password_reset"),
url(r'^password_reset/mailed/$',
'django.contrib.auth.views.password_reset_done',{'template_name': 'resetpassword_mailed.html'}),
url(r'^password_reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
'django.contrib.auth.views.password_reset_confirm',
{'post_reset_redirect' : '/password_reset/complete/'}),
url(r'^password_reset/complete/$',
'django.contrib.auth.views.password_reset_complete',{'template_name': 'resetpassword_complete.html'}),
and settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mail.ru'
EMAIL_HOST_USER = 'noreply#mysite.com'
DEFAULT_FROM_EMAIL = 'noreply#mysite.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
URL routing works just fine, however email are not being sent.
If I try to use Django shell and test sending:
email = EmailMessage('Subject', 'Body', to=['test#email.com'])
email.send()
And it works just fine as well.
How could I fix this? I don't get any error messages and don't know how could I debug this.
UPD
I have found out that in django/contrib/auth/views.py: password_reset method I always go to
else:
post_reset_redirect = resolve_url(post_reset_redirect)
part and never to actually sending email. How's that?
if post_reset_redirect is None:
post_reset_redirect = reverse('password_reset_done')
else:
post_reset_redirect = resolve_url(post_reset_redirect)
if request.method == "POST":
form = password_reset_form(request.POST)
if form.is_valid():
print 'reset form valid'
opts = {
'use_https': request.is_secure(),
'token_generator': token_generator,
'from_email': from_email,
'email_template_name': email_template_name,
'subject_template_name': subject_template_name,
'request': request,
'html_email_template_name': html_email_template_name,
}
if is_admin_site:
opts = dict(opts, domain_override=request.get_host())
form.save(**opts)
return HttpResponseRedirect(post_reset_redirect)
If the user has no password (e.g. created with create_user()), the password reset won't send anything! Make sure you create a password as well via:
password = User.objects.make_random_password()
Then, you also need to set the password and save, for example
user.set_password(password)
user.save()
Could be a trivial question but the user you are using to test has a valid email set? If it's empty will not send the email neither raise an exception.
Check the send method source code.
Other way to see if the email is being generated is use the console backend:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
and look at the console because the email should appears there.
Thanks

Categories

Resources