Django. Sending email with an application - python

I started a new application gmail and configured settings in settings.py with my gmail account
I'm new in django and I don't know how to send emails to my website users
I would like to create a link that when I open it my user will get a message from me
I have edited views.py but I don't know what my function "wyslij" should return
from django.shortcuts import render
from django.core.mail import send_mail
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.models import User
from userprofile.models import UserProfile
#user_passes_test(lambda u: u.is_superuser)
# Create your views here.
def wyslij(request):
# Create the HttpResponse object with the appropriate PDF headers.
uzyt = UserProfile.objects.all().order_by('user_id')
for z, uzyt in enumerate(UserProfile.objects.all()):
send_mail('The exam is comming', 'Hi, Your exam will be tomorrow!', 'santa.claus.for.grace#gmail.com', [uzyt.email], fail_silently=False)
return response
In urls.py
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^accounts/wyslij/$', 'gmail.views.wyslij'),
)

In settings.py, you have to add these liner:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'xxxxxxxxxxx#gmail.com'
EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxx'
EMAIL_PORT = 587 #or try with 25

https://docs.djangoproject.com/en/1.7/topics/email/
be sure to name your EMAIL variables and .gitignore your settings file

Related

Password Reset Email Not Being Sent in Django

First of all, I'd just like to clarify that I've looked at all the other questions in regard to this on Stack Overflow and I haven't been able to resolve the issue.
So, the issue I'm having is that I'm not receiving a password reset email on my site, even though everything indicates that the email has been sent. I say this because I get the confirmation on my screen that the email has been sent and I also get the email displayed in the console (see below).
Here are my email settings:
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
EMAIL_USE_TLS = True
EMAIL_HOST = "localhost"
EMAIL_PORT = 25
EMAIL_HOST_USER = os.environ.get("EMAIL_ADDRESS")
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_PASSWORD")
Here are my password reset URLs:
from django.conf.urls import url
from django.core.urlresolvers import reverse_lazy
from accounts.views import change_password
from django.contrib.auth.views import (
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete)
urlpatterns = [
url(r'^$', password_reset, name='password_reset'),
url(r'^reset-password/done/$', password_reset_done,
name='password_reset_done'),
url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',
password_reset_confirm, name='password_reset_confirm'),
url(r'^complete/$', password_reset_complete,
name='password_reset_complete'),
url(r'^change-password/$', change_password, name='change_password'),
]
Any feedback is greatly appreciated!
Thanks in advance.
You specified as EMAIL_BACKEND:
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
This is a Console backend [Django-doc], so it does not send an email, but prints the email to the console. This can for example be used for testing purposes.
You can specify as backend for example the SMTP backend [Django-doc]:
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"

2 password reset e-mails in Django every time I try to reset a password

I am a beginner in Django and i have been following an online tutorial to build a web application. I had been trying to add the password reset functionality to the application for the past few days. I set up a google app password and finally got the password reset to work. But now, every time i try to reset a password, i receive 2 password reset emails on my email account. I have reset the password successfully a few times but i continue to receive two emails every time i try to reset a password. I tried to look for answers online but couldn't find anything. I have also cross-checked my code with the tutorial. Here are some code snippets that might be relevant:
Project settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS')
Project urls.py:
from django.contrib import admin
from django.urls import path, include
from users import views as user_views
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'),
name='password_reset'),
path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(
template_name='users/password_reset_done.html'), name='password_reset_done'),
path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(
template_name='users/password_reset_confirm.html'), name='password_reset_confirm'),
path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(
template_name='users/password_reset_complete.html'), name='password_reset_complete'),
path('profile/', user_views.profile, name='profile'),
path('', include('blog.urls')),
]
Any help will be highly appreciated. Thanks!
PS: This is my first question on StackOverflow. Please let me know if i can improve it in any way.
I had the same problem, but the answer is really simple:
I bet you have 2 Django accounts which use the same mail address. In my case I have a normal user account but I'm also the administrator of Django and use the same mail address for the admin account too. :)
Django loops through all accounts and send a mail to every user where the mail address matches.

Send email with Sendgrid in Django

I'm trying to send emails from a Django app using Sendgrid. I've tried many configurations, but I still doesn't get any email on my Gmail account. You can see my configurations bellow:
settings.py:
SEND_GRID_API_KEY = 'APIGENERATEDONSENDGRID'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'mySENDGRIDusername'
EMAIL_HOST_PASSWORD = 'myEMAILpassword' #sendgrid email
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'MYEMAIL' #sendgrig email
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import ContactForm
from django.core.mail import send_mail
from django.conf import settings
from django.template.loader import get_template
def index(request):
return render(request, 'index.html')
def contact(request):
success = False
form = ContactForm(request.POST)
if request.method == 'POST':
name = request.POST.get("name")
email = request.POST.get("email")
message = request.POST.get("message")
subject = 'Contact from MYSITE'
from_email = settings.DEFAULT_FROM_EMAIL
to_email = [settings.DEFAULT_FROM_EMAIL]
message = 'Name: {0}\nEmail:{1}\n{2}'.format(name, email, message)
send_mail(subject, message, from_email, to_email, fail_silently=True)
success = True
else:
form = ContactForm()
context = {
'form': form,
'success': success
}
return render(request, 'contact.html',context)
Do you guys know what could be happening? I can get the email locally and I can see it in the terminal, but no email can be sent at all.
I struggled a bit when trying to set up the sendgrid with Django using SMTP. What worked for me is the following:
settings.py
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey'
EMAIL_HOST_PASSWORD = 'sendgrid-api-key' # this is your API key
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = 'your-email#example.com' # this is the sendgrid email
I used this configuration, and it worked properly, and I strongly suggest using environment variables to fill EMAIL_HOST_PASSWORD and DEFAULT_FROM_EMAIL, so the code will be as follows:
import os # this should be at the top of the file
# ...
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", "")
Then, when sending an email I used the following code:
from django.conf import settings
from django.core.mail import send_mail
send_mail('This is the title of the email',
'This is the message you want to send',
settings.DEFAULT_FROM_EMAIL,
[
settings.EMAIL_HOST_USER, # add more emails to this list of you want to
]
)
Try adding these to right bellow the your declaration in settings
SENDGRID_SANDBOX_MODE_IN_DEBUG=False
SENDGRID_ECHO_TO_STDOUT=False
DO this settings on your settings.py file
EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend'
SENDGRID_SANDBOX_MODE_IN_DEBUG = False
FROM_EMAIL = 'youremail#gmail.com' # replace with your address
SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY')
dont use debug true if you run this on your local server.
This is working for me, I think the SendGrid guide might be missing the DEFAULT_FROM_EMAIL which seems necessary if you haven't set it up on their website.

Email verification and password reset - django rest framework and angularjs

How do I implement the built in views for password-reset in the django.rest.auth and how do I create an email verification system for registration using the django rest framework and angularjs?
I have been searching for a tutorial or some good documentation that on how to implement django's send_email function in a website using the django rest framework and angular js but I haven't been able to find any.
What I need...
when a new user registers a url must be generated for them to confirm their email address
this url must be automatically sent to the user's given email
after the user is sent to this link and confirms their email address their status must be changed from new_user.is_active = False to new_user.is_active = True
What I have...
registration form that sends a post request to my register endpoint
the new user data is then unpacked, validated, and saved in my register view
in settings.py i have added this...
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 587
in my urls.py i have added this...
from django.conf.urls import url
from rest_auth.views import PasswordResetView, PasswordResetConfirmView
urlpatterns = [
url(r'^password/reset/$', PasswordResetView.as_view(), name='password_reset'),
url(r'^password/reset/confirm/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
]
So my question is how do I implement these views and urls to my project and how to I create email confirmation using the from django.core.mail import send_mail
Thanks in advance
After the user fills the registration form you could ask for a verification code. This verification code will be sent to the email address provided in the registration form. On correctly entering the verification code you can set the users to active.
For anyone still looking for solutions, django-allauth is a good choice. you can override PASSWORD_RESET_CONFIRM_SERIALIZER to make the user active.

Server error 500 on sending email on Heroku

I have a Django project. The user fills the form and then I receive a notification about new order. Localy, on my computer everything is ok. I deploy my application on Heroku and on the site I cannot send emails. I receive error 500.
This is my code:
settings.py
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'mymail#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL='sitename'
views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import render_to_string
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .forms import OrderForm
def contact(request):
company='no company'
if request.method == 'POST' :
form=OrderForm(request.POST)
if form.is_valid():
company=form.cleaned_data['company']
try:
msg_plain = render_to_string('../templates/publicity_agency/email.txt', {'company':company})
msg_html = render_to_string('../templates/publicity_agency/email.html', {'company':company})
msg_plain_client = render_to_string('../templates/publicity_agency/email_client.txt')
msg_html_client = render_to_string('../templates/publicity_agency/email_client.html')
send_mail('New order',msg_plain,'Notification <myemail#gmail.com>', ['myemail#gmail.com'], html_message=msg_html)
send_mail('Order',msg_plain_client,'Order <myemail#gmail.com>', [email], html_message=msg_html_client)
except BadHeaderError:
return HttpResponse('Invalid header found')
return redirect('contact')
else:
form=OrderForm()
return render(request, 'publicity_agency/contacts.html', {'company':company})

Categories