Sending emails with Django and Post Office - python

I have some trouble setting up an email option for my django project.
I am using post office for the backend, but I can't seem to get anything to queue.
views.py:
from django.views.generic import TemplateView
from post_office import mail
class EmailView(TemplateView):
model = Customer
mail.send(
'a.sophiewirth#gmail.com', # List of email addresses also accepted
'your.generic.test.email#gmail.com',
subject='My email',
message='Hi there!',
html_message='Hi <strong>there</strong>!',
)
template_name = 'customers/send_email.html'
settings.py:
# using post office as the default email backend
EMAIL_BACKEND = 'post_office.EmailBackend'
POST_OFFICE = {
'DEFAULT_PRIORITY' : 'now'
}
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "your.generic.test.email#gmail.com"
EMAIL_PORT = 25 # default smtp port
EMAIL_HOST_PASSWORD = "password"
EMAIL_USE_TLS = False
DEFAULT_FROM_EMAIL = 'your.generic.test.email#gmail.com'
urls.py:
from django.conf.urls import patterns, include, url
from customers.views import CustomerList, CreateCustomerView, CustomerUpdateView, EmailView
from . import views
urlpatterns = patterns('',
url(r'^$', CustomerList.as_view(), name="customer-list"),
url(r'^create-customer$', CreateCustomerView.as_view(), name="create-customer"),
url(r'^customer-update/(?P<pk>\d+)$', CustomerUpdateView.as_view(), name="customer-update"),
url(r'^send-email$', EmailView.as_view(), name="send-email"),
)
send_email.html itself is pretty empty thus far, it just contains a paragraph to tell you that you sent an email.
Can anyone tell me why nothing is sending? Also, how can I get the recipient of the email into the View, as the specific user I want to send the mail to?
Thank you very much :)

I have both djcelery and Django celery email installed. This is in an older project and I believe djcelery is no longer needed but my setup should still give you a start. My Django settings include the following:
import djcelery
...
djcelery.setup_loader()
EMAIL_BACKEND = 'post_office.EmailBackend'
POST_OFFICE_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'
My project also includes a shell script, which I run to start and configure the celery daemon. My project is running in a virtualenv so some of this may not be needed for you.
#!/bin/bash
set -e
# user/group to run as
USER=your_username
GROUP=your_groupname
cd /path/to/virtualenv/
source ./bin/activate
cd /path/to/directory/containing/manage.py/
exec python manage.py celeryd --settings=directory.path.settings.py
Running the shell script should show you a running celery process and your emails should now send and queue happily.

remove default priority now and add 'CELERY_ENABLED': True, to POST_OFFICE settings like this:
POST_OFFICE = {
'CELERY_ENABLED': True,
}
after this when u start celery worker you should see 2 tasks received from
post_office
post_office.tasks.cleanup_expired_mails
post_office.tasks.send_queued_mail

Related

Python allauth disable mail confirmation for oauth apps

I'm new into python and django and I'm developing an app liked to a django server that works as oauth provider.
I've set this on settings.py file:
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'
ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_EMAIL_REQUIRED = True
But if I did not add the verified flag on the mail section in django I cannot login into the app.
What should I do in order to remove the verification step?
remove those tree lines and paste this, I hope it works
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

What am I unable to send email using Django?

I have turned on the 'allow less secure apps' on my google account.
But when I submit the password reset form, it goes to the password_reset_done.html and DOESN'T show any error. But the mail is not sending. It's neither in my sentbox nor in the inbox of the email it's supposed to send to.
This is what my urls.py looks like :
from django.contrib.auth import views as auth_views
path('password_reset/',
auth_views.PasswordResetView.as_view(template_name="my_app/password_reset.html"),
name="password_reset"),
path('password_reset/done/',
auth_views.PasswordResetDoneView.as_view(template_name="my_app/password_reset_done.html"),
name="password_reset_done"),
path('password-reset-confirm/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(template_name="my_app/password_reset_confirm.html"),
name="password_reset_confirm" ),
path('reset_password/',
auth_views.PasswordResetCompleteView.as_view(template_name="my_app/password_reset_complete.html"),
name="password_reset_complete" ),
And here is the settings.py file:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'my_g_mail_id_here#domain.com'
EMAIL_HOST_PASSWORD = '**********'
I have literally read every other question and tried everything. Nothing is working for me.
I am dying here to find out a solution, please help.
Don't use Gmail for this. It's not designed for programmatic email sending.
Instead, use something like SendGrid or Mailgun. Both have inexpensive or free starter plans.
I found the solution. I was not registering user's email ID's through the Djangos default registration form.
Tweaked it a little to add the email field in the form and then the users started recieving the email.
Nothing wrong in the conf file.

Django registration email not sending

I've been trying to get the django-registration-redux account activation email to send to newly registered users.
I've gotten all non-email related parts to work, such as loggin in/out and actually registering the user! When i register, it automatically logs my in as that user. But i never get the activation email.
I've tried various different things to try get this to work, I've followed some tutorials on setting whole thing up but the emails still dont work.
heres some of the code setup, im using registration templates that i downloaded online.
settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'registration',
'synths',
)
# user reg settings
REGISTRATION_OPEN = True
ACCOUNT_ACTIVATION_DAYS = 7
REGISTRATION_AUTO_LOGIN = True
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/login/'
# i tried including this line but still nothing
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# email
# first i tried setting up the debbuging server with this CMD line
# python -m smtpd -n -c DebuggingServer localhost:1025
# i dont know if it worked!, i got no errors but the cursor just
# sat there blinking at me! i was expecting some output to tell me
# the server had started
# these were the settings i used for that
EMAIL_HOST = '127.0.0.1'
EMAIL_PORT = 1025
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
# then i tried using my own address and smtp.live.com
EMAIL_HOST = 'smtp.live.com'
EMAIL_PORT = 25
EMAIL_HOST_USER = 'myemailaddress#hotmail.com'
EMAIL_HOST_PASSWORD = '123123abcabc'
# still nothing
am i missing any important settings here?
urls.py
# included amongst my other urls
(r'^accounts/', include('registration.backends.simple.urls')),
seems all in order with the tutorials and documentation. like i said, registration works perfectly bar the emails.
one thing ive noticed is that you probably shouldn't have auto loggin = True if you want a user to activate their accounts, but commenting that line out didnt change anything, i still got logged in automatically after registering. Seems like a minor aside but maybe this has something to do with the emails not working?
i dunno, im lost with it. Either im missing some settings, the code doesnt work, python smtpd doesnt work, or my smtp.live.com settings are wrong!
any insigths greatly appreciated!
EDIT: when trying the 'reset password' email function i get this error
SMTPException at /accounts/password/reset/
SMTP AUTH extension not supported by server.
Request Method: POST
Request URL: http://localhost:8000/accounts/password/reset/
Django Version: 1.7.6
Exception Type: SMTPException
Exception Value: SMTP AUTH extension not supported by server.
Exception Location: C:\Python34\lib\smtplib.py in login, line 613
Python Executable: C:\Python34\python.exe
Python Version: 3.4.3
EDIT 2: using these settings i get the the password/reset/done page but recieve no actual email
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = '127.0.0.1'
EMAIL_PORT = 1025
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
will only display the email on the console.
Instead you should use
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
Moreover it is more convenient to use a existing smtp server like gmail
For that you need to add these to your django settings file
EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST ='smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'youruser#gmail.com'
EMAIL_HOST_PASSWORD = 'gmail app password' #This is not your gmail password.
EMAIL_USE_TLS = True
More help on the password can be found here
You may want to try adding a DEFAULT_FROM_EMAIL setting and setting these settings:
EMAIL_USE_TLS = True
EMAIL_USE_SSL = True
This will allow Django to use secure email-sending.
Check your urls.py file, and make sure you are using the hmac not the simple
urlpatterns = [
#...
url(r'^accounts/', include('registration.backends.hmac.urls')),
]
Also, in your setting.py, INSTALLED_APPS, make sure that the 'registration' is before django.contrib.auth.
INSTALLED_APPS = [
#.....
'registration',
'django.contrib.auth',
#...
]
I know this is an old question, but I thought it would help anybody else looking for the answer. You have setup your urlconf to use the one step registration. Below is a snippet from their docs -
This backend’s workflow is deliberately as simple as possible:
A user signs up by filling out a registration form.
The user’s account is created and is active immediately, with no intermediate confirmation or activation step.
The new user is logged in immediately.
If you want to see the emails in the console, use the following urlconf instead -
url(r'^account/', include('registration.backends.default.urls')),
Hope that helps.

Unable log in to the django admin page with a valid username and password

I can’t log in to the django admin page. When I enter a valid username and password, it just brings up the login page again, with no error messages
This question is in the django FAQ, but I've gone over the answers there and still can't get past the initial login screen.
I'm using django 1.4 on ubuntu 12.04 with apache2 and modwsgi.
I've confirmed that I'm registering the admin in the admin.py file, made sure to syncdb after adding INSTALLED_APPS.
When I enter the wrong password I DO get an error, so my admin user is being authenticated, just not proceeding to the admin page.
I've tried both setting SESSION_COOKIE_DOMAIN to the machine's IP and None. (Confirmed that the cookie domain shows as the machine's IP in chrome)
Also, checked that the user authenticates via the shell:
>>> from django.contrib.auth import authenticate
>>> u = authenticate(username="user", password="pass")
>>> u.is_staff
True
>>> u.is_superuser
True
>>> u.is_active
True
Attempted login using IE8 and chrome canary, both results in the same return to the login screen.
Is there something else I'm missing????
settings.py
...
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.staticfiles',
'django.contrib.gis',
'myapp.main',
)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 86400 # sec
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'DSESSIONID'
SESSION_COOKIE_SECURE = False
urls.py
from django.conf.urls.defaults import * ##UnusedWildImport
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^bin/', include('myproject.main.urls')),
(r'^layer/r(?P<layer_id>\d+)/$', "myproject.layer.views.get_result_layer"),
(r'^layer/b(?P<layer_id>\d+)/$', "myproject.layer.views.get_baseline_layer"),
(r'^layer/c(?P<layer_id>\d+)/$', "myproject.layer.views.get_candidate_layer"),
(r'^layers/$', "myproject.layer.views.get_layer_definitions"),
(r'^js/mapui.js$', "myproject.layer.views.view_mapjs"),
(r'^tilestache/config/$', "myproject.layer.views.get_tilestache_cfg"),
(r'^admin/', include(admin.site.urls)),
(r'^sites/', include("myproject.sites.urls")),
(r'^$', "myproject.layer.views.view_map"),
)
urlpatterns += staticfiles_urlpatterns()
Apache Version:
Apache/2.2.22 (Ubuntu) mod_wsgi/3.3 Python/2.7.3 configured
Apache apache2/sites-available/default:
<VirtualHost *:80>
ServerAdmin ironman#localhost
DocumentRoot /var/www/bin
LogLevel warn
WSGIDaemonProcess lbs processes=2 maximum-requests=500 threads=1
WSGIProcessGroup lbs
WSGIScriptAlias / /var/www/bin/apache/django.wsgi
Alias /static /var/www/lbs/static/
</VirtualHost>
<VirtualHost *:8080>
ServerAdmin ironman#localhost
DocumentRoot /var/www/bin
LogLevel warn
WSGIDaemonProcess tilestache processes=2 maximum-requests=500 threads=1
WSGIProcessGroup tilestache
WSGIScriptAlias / /var/www/bin/tileserver/tilestache.wsgi
</VirtualHost>
UPDATE
The admin page does proceed when using the development server via runserver so it seems like a wsgi/apache issue. Still haven't figured it out yet.
SOLUTION
The problem was that I had the settings file SESSION_ENGINE value set to 'django.contrib.sessions.backends.cache' without having the CACHE_BACKEND properly configured.
I've changed the SESSION_ENGINE to 'django.contrib.sessions.backends.db' which resolved the issue.
Steps to debug:
Make sure that your Database is synced
Double check that you have a django_session table
Try to authenticate
Do you see a record being created in the django_session table?
IF NOT
remove non-standard settings
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_COOKIE_AGE = 86400 # sec
SESSION_COOKIE_DOMAIN = None
SESSION_COOKIE_NAME = 'DSESSIONID'
SESSION_COOKIE_SECURE = False
Make sure that your Database is synced
Double check that you have a django_session table
Try to authenticate
Do you see a record being created in the django_session table?
Let me know if this turns up any useful debug.
Sample settings file: https://github.com/fyaconiello/Django-Blank-Bare-Bones-CMS/blob/master/dbbbcms/settings.py
>>> from django.contrib.auth import authenticate
>>> u = authenticate(username="user", password="pass")
>>> u.is_staff = True
>>> u.is_superuser = True
Is there something else I'm missing?
u.is_active should be True
I had this problem. The issue is that in production I set two variables to True that allowed me to connect to the site using https.
SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE should be set to False if you are developing on localhost http. Changing these two variables to False allowed me to sign into the admin site when developing locally.
I don't believe the admin password is stored in the settings.py file. It's created when you first syncdb. I am thinking you either skipped creating the superuser or just made a typo.
Try running in terminal at your projects root.:
python django-admin.py createsuperuser
That will allow you to retype your admin login. Also seen here https://docs.djangoproject.com/en/dev/ref/django-admin/
Did you try by creating the user with :
python manage.py createsuperuser
I have the same issue when I create the db on a test machine and migrate it to the deployment server...
We had a similar issue in our app and these might help:
Use cleanup command to clear older sessions from django_sessions
Check the cookie size in firefox(firebug) or chrome developer tools. Because messaging is enabled by default in admin(django.contrib.messages.middleware.MessageMiddleware), the cookie size sometimes get larger than 4096 bytes with multiple edits and deletes. One quick test is to delete the "message" cookie and see if you can login after that.
And we actually ended up switching to nginx/uwsgi route because of this and other memory related issues with apache. Haven't seen this repeated in nginx since.
After not being able to log in myself, I saw in the comment above someone mentioned about removing non-standard settings.
Adding this to my local settings solved it for me
SESSION_COOKIE_SECURE = False
sounds like a session problem because after the post you get redirected and immediately the system has forgotten that you logged in.
try the following:
check your session backend is working.
swap it with cache backend if you use db cache backend to check if transaction middleware is messing around.
try db backend and check if there are sessions stored in the db table
I'm not exactly sure, but the problem might be with your URL configuration, concretely in these two lines:
(r'^admin/', include(admin.site.urls)),
(r'^sites/', include("myproject.sites.urls")),
A longer time ago, I had trouble with browsing the admin of my Django project because a single URL configuration overwrote a part of the admin url. It seems that Django doesn't like it when you specify a custom URL configuration that contains elements which are also part of the admin URL. In your case, you have the app django.contrib.sites enabled in your settings.py. You can access the admin panel of this app by going to http://127.0.0.1:8000/admin/sites/. It might be that your URL configuration with r'^sites/' in it overrides a part of the admin url. Try renaming this specific URL configuration or disable django.contrib.sites in INSTALLED_APPS for testing purposes.
Please note that this is just an assumption. All I know is that Django's admin panel is a bit picky about URL configurations using similar names like its own URLs. I cannot test it myself at the moment. But maybe this helps you a bit.
Check that you have at least one site to work with.
>>> from django.contrib.sites.models import Site
>>> Site.objects.count()
(0.048) SELECT COUNT(*) FROM `django_site`; args=()
1
If you see 0 here - create one.
Checking some other articles on this topic, it could be related to sys.path. Can you check and compare sys.path when running the dev server and when running WSGI.
For some details, have a look this and that article. But I would check the sys.path first, before going into the details of this article.
Make sure your database user table having following entry is true:
is_staff => True (if exit).
is_active => True .
is_superuser => True.
This is not OP's issue, but I am posting this answer in the hopes someone may have gone down the same path as I and arrived at this question as a result.
I came back to an old codebase after a year and was denied access to the admin panel despite all of the usual checks passing (user is present, nothing looks incorrect in the database, all debug modes are on, etc). Unfortunately, I had forgotten that the admin sign in page was not at the usual /admin route, but rather at an alternate route. The /admin page was a fake sign in page that always resulted in a failed sign in.
This setup was created using the app django-admin-honeypot.
For me below settings worked on localhost
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
]
SESSION_COOKIE_DOMAIN = None
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
Disclaimer: I cannot add comments yet, so I have to ask clarification here proposing a solution at the same time. Sorry for that.
Is the user logged-out immediately after logging-in? something like this issue
You can check it in many ways, I suggest to add a hook to the logout signal (you can put it in your models.py):
from django.contrib.auth.signals import user_logged_out
def alertme(sender, user, request, **kwargs):
print ("USER LOGGED OUT!") #or more sophisticate logging
user_logged_out.connect(alertme)
then try to log in and check if the message appears in your console. If it appears, then you have to check if you have a redirect or a customized template calling logout after login. Hope it helps you find the issue.
I had same problem and it was just solved after restarting server :
systemctl restart nginx
You can ensure, the created user has been flagged as Is_staff = True, I sometimes forget to flag this to allow users to login to django admin
I had a related issue where I'd try to log in and the page would hang before the socket would eventually be killed. It turned out that I was indeed being logged in, but one of the login signal processors was freezing.
Celery couldn't pass its asynchronous tasks to RabbitMQ because the RabbitMQ server wasn't able to start.
For me, I could not login to the admin page in firefox but could login in chrome.
The problem was that I had CSRF_COOKIE_PATH set in my settings.py.
Never use that. It does not not work properly on django 1.8.
What I did was to navigate manually to the url I wanted to visit.
So like: http://wildlifeapi.herokuapp.com/admin/ was returning the awful Heroku application error.
So what I did was to visit http://wildlifeapi.herokuapp.com/admin/api/animal/ and BINGO! it worked.
The funny thing is that it works well on my phone. It's probably a django redirection bug.
My issue was that My Admin Page was not loading and not working. Here is what I did:
pip uninstall django
pip install django==2.2
For more Detail Check Django Documentation.
For anyone who encountered this problem after upgrading Django, the problem could be that the signature of the authenticate function has changed at some point. If the signature doesn't match what's expected, the backend is just ignored. So make sure your custom authentication backend authenticate method looks like this:
class EmailUsernameAuthenticationBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
# ...
And NOT like this (without the request argument):
class EmailUsernameAuthenticationBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
A bit late for the party, but to me it was different and surprinsingly simpler: for whatever reason my superuser account was gone so, obviously, the solution was I had to create it again.
I'm 99% sure I had executed migrate and makemigrations a few times after having created my superuser, but go figure...
It took me about a whole hour to finally figure it out, however. None of the variables discussed here existed in my settings.py -and still don't to the present moment- (probably because it has been nearly 10 years, so things might have changed considerably), like SESSION_ENGINE, SESSION_COOKIE_DOMAIN, CACHE_BACKEND, django_session table...
Also, Django's FAQ on this subject mentions checking if my account is_active and is_staff, but unfortunately without ever mentioning how to do it.
For my case it is always the issue with SESSION_COOKIE_DOMAIN:
On local machine I set it like:
SESSION_COOKIE_DOMAIN = 'localhost'
On remote one, domain one, like:
SESSION_COOKIE_DOMAIN = 'yourdomainname.com'
In my case, I was not able to log in because I was using email in the place of username (which in my case was "admin") to try to log in. So do ensure you're using the right username and password to log in
Use some other virtual environment.it worked for me when i used conda environment.

Pinax Email Verification not working

I have installed pinax on my local and I try to sign-up on it. but the email verification is not working, so I look over the internet on how to config about the email verification but failed.
I try also the forgot password but it requires the email address to be confirmed.
I also try to put this code in settings.py
EMAIL_HOST = '...'
EMAIL_PORT = ..
EMAIL_HOST_USER = '...'
EMAIL_HOST_PASSWORD = '..'
EMAIL_SUBJECT_PREFIX = '..'
EMAIL_USE_TLS = True
EMAIL_ADMIN = '...'
but still not working.
Does anyone have an idea on why my pinax's email verification is not working?
Did you check your spam folder?
Also some apps tell Django to silently ignore EMail sending errors.
Try this quick example in the shell you get from python manage.py shell and see if it shows you any errors.

Categories

Resources