1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-09-11 03:41:12 +00:00

Added email sending settings

This commit is contained in:
zhengxie
2013-01-09 17:28:56 +08:00
parent 9cbd7f20a4
commit db23497e69
6 changed files with 85 additions and 31 deletions

View File

@@ -214,7 +214,7 @@ LOGGING = {
'disable_existing_loggers': True, 'disable_existing_loggers': True,
'formatters': { 'formatters': {
'standard': { 'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' 'format': '%(asctime)s [%(levelname)s] %(name)s:%(lineno)s %(funcName)s %(message)s'
}, },
}, },
'handlers': { 'handlers': {
@@ -251,6 +251,17 @@ LOGGING = {
} }
} }
#################
# Email sending #
#################
SEND_EMAIL_ON_ADDING_SYSTEM_MEMBER = True # Whether to send email when a system staff adding new member.
SEND_EMAIL_ON_RESETTING_USER_PASSWD = True # Whether to send email when a system staff resetting user's password.
#####################
# External settings #
#####################
def load_local_settings(module): def load_local_settings(module):
'''Import any symbols that begin with A-Z. Append to lists any symbols '''Import any symbols that begin with A-Z. Append to lists any symbols
that begin with "EXTRA_". that begin with "EXTRA_".

View File

@@ -26,7 +26,7 @@ from seahub.contacts.signals import mail_sended
from seahub.share.models import FileShare from seahub.share.models import FileShare
from seahub.views import validate_owner, is_registered_user from seahub.views import validate_owner, is_registered_user
from seahub.utils import render_permission_error, string2list, render_error, \ from seahub.utils import render_permission_error, string2list, render_error, \
gen_token, gen_shared_link gen_token, gen_shared_link, IS_EMAIL_CONFIGURED
try: try:
from seahub.settings import CLOUD_MODE from seahub.settings import CLOUD_MODE
@@ -467,6 +467,10 @@ def send_shared_link(request):
result = {} result = {}
content_type = 'application/json; charset=utf-8' content_type = 'application/json; charset=utf-8'
if not IS_EMAIL_CONFIGURED:
data = json.dumps({'error':_(u'Sending shared link failed. Email service is not properly configured, please contact administrator.')})
return HttpResponse(data, status=500, content_type=content_type)
from seahub.settings import SITE_NAME from seahub.settings import SITE_NAME
form = FileLinkShareForm(request.POST) form = FileLinkShareForm(request.POST)

View File

@@ -8,6 +8,7 @@ from django.utils.translation import ugettext_lazy as _
from django.utils.http import int_to_base36 from django.utils.http import int_to_base36
from seahub.base.accounts import User from seahub.base.accounts import User
from seahub.utils import IS_EMAIL_CONFIGURED
class AuthenticationForm(forms.Form): class AuthenticationForm(forms.Form):
""" """
@@ -61,6 +62,9 @@ class PasswordResetForm(forms.Form):
""" """
Validates that a user exists with the given e-mail address. Validates that a user exists with the given e-mail address.
""" """
if not IS_EMAIL_CONFIGURED:
raise forms.ValidationError(_(u'Failed to send email, email service is not properly configured, please contact administrator.'))
email = self.cleaned_data["email"] email = self.cleaned_data["email"]
# TODO: add filter method to UserManager # TODO: add filter method to UserManager

View File

@@ -1,8 +1,10 @@
import re import re
import logging
from django.conf import settings from django.conf import settings
# Avoid shadowing the login() view below. # Avoid shadowing the login() view below.
from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import csrf_protect
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.contrib import messages
from django.shortcuts import render_to_response, get_object_or_404 from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.sites.models import Site, RequestSite from django.contrib.sites.models import Site, RequestSite
from django.http import HttpResponseRedirect, Http404 from django.http import HttpResponseRedirect, Http404
@@ -20,6 +22,9 @@ from auth.tokens import default_token_generator
from seahub.base.accounts import User from seahub.base.accounts import User
# Get an instance of a logger
logger = logging.getLogger(__name__)
@csrf_protect @csrf_protect
@never_cache @never_cache
def login(request, template_name='registration/login.html', def login(request, template_name='registration/login.html',
@@ -126,7 +131,15 @@ def password_reset(request, is_admin_site=False, template_name='registration/pas
opts['email_template_name'] = email_template_name opts['email_template_name'] = email_template_name
if not Site._meta.installed: if not Site._meta.installed:
opts['domain_override'] = RequestSite(request).domain opts['domain_override'] = RequestSite(request).domain
try:
form.save(**opts) form.save(**opts)
except Exception, e:
logger.error(str(e))
messages.error(request, _(u'Failed to send email, please contact administrator.'))
return render_to_response(template_name, {
'form': form,
}, context_instance=RequestContext(request))
else:
return HttpResponseRedirect(post_reset_redirect) return HttpResponseRedirect(post_reset_redirect)
else: else:
form = password_reset_form() form = password_reset_form()

View File

@@ -28,6 +28,11 @@ try:
from settings import DOCUMENT_CONVERTOR_ROOT from settings import DOCUMENT_CONVERTOR_ROOT
except ImportError: except ImportError:
DOCUMENT_CONVERTOR_ROOT = None DOCUMENT_CONVERTOR_ROOT = None
try:
from settings import EMAIL_HOST
IS_EMAIL_CONFIGURED = True
except ImportError:
IS_EMAIL_CONFIGURED = False
import settings import settings
@@ -722,3 +727,4 @@ def show_delete_days(request):
days = 7 days = 7
return days return days

View File

@@ -8,6 +8,7 @@ import tempfile
import sys import sys
import urllib import urllib
import urllib2 import urllib2
import logging
from urllib import quote from urllib import quote
from django.core.cache import cache from django.core.cache import cache
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
@@ -69,7 +70,7 @@ from utils import render_permission_error, render_error, list_to_string, \
calculate_repo_last_modify, valid_previewed_file, \ calculate_repo_last_modify, valid_previewed_file, \
check_filename_with_rename, get_accessible_repos, EMPTY_SHA1, \ check_filename_with_rename, get_accessible_repos, EMPTY_SHA1, \
get_file_revision_id_size, get_ccnet_server_addr_port, \ get_file_revision_id_size, get_ccnet_server_addr_port, \
gen_file_get_url, string2list, MAX_INT, \ gen_file_get_url, string2list, MAX_INT, IS_EMAIL_CONFIGURED, \
gen_file_upload_url, check_and_get_org_by_repo, \ gen_file_upload_url, check_and_get_org_by_repo, \
get_file_contributors, EVENTS_ENABLED, get_user_events, get_org_user_events, \ get_file_contributors, EVENTS_ENABLED, get_user_events, get_org_user_events, \
get_starred_files, star_file, unstar_file, is_file_starred, get_dir_starred_files, \ get_starred_files, star_file, unstar_file, is_file_starred, get_dir_starred_files, \
@@ -80,7 +81,11 @@ try:
DOCUMENT_CONVERTOR_ROOT += '/' DOCUMENT_CONVERTOR_ROOT += '/'
except ImportError: except ImportError:
DOCUMENT_CONVERTOR_ROOT = None DOCUMENT_CONVERTOR_ROOT = None
from settings import FILE_PREVIEW_MAX_SIZE, INIT_PASSWD, USE_PDFJS from settings import FILE_PREVIEW_MAX_SIZE, INIT_PASSWD, USE_PDFJS,\
SEND_EMAIL_ON_ADDING_SYSTEM_MEMBER, SEND_EMAIL_ON_RESETTING_USER_PASSWD
# Get an instance of a logger
logger = logging.getLogger(__name__)
@login_required @login_required
def root(request): def root(request):
@@ -1987,16 +1992,8 @@ def send_user_reset_email(request, email, password):
'password': password, 'password': password,
'site_name': settings.SITE_NAME, 'site_name': settings.SITE_NAME,
} }
try:
send_mail(_(u'Password Reset'), t.render(Context(c)), send_mail(_(u'Password Reset'), t.render(Context(c)),
None, [email], fail_silently=False) None, [email], fail_silently=False)
msg = _('Successfully resetting password to %(passwd)s, an email has been sent to %(user)s.') % \
{'passwd': password, 'user': email}
messages.success(request, msg)
except:
msg = _('Successfully resetting password to %(passwd)s, but failed to send email to %(user)s, please check your email configuration.') % \
{'passwd':password, 'user': email}
messages.error(request, msg)
@login_required @login_required
@sys_staff_required @sys_staff_required
@@ -2007,10 +2004,24 @@ def user_reset(request, user_id):
user.set_password(INIT_PASSWD) user.set_password(INIT_PASSWD)
user.save() user.save()
if hasattr(settings, 'EMAIL_HOST'): if IS_EMAIL_CONFIGURED:
if SEND_EMAIL_ON_RESETTING_USER_PASSWD:
try:
send_user_reset_email(request, user.email, INIT_PASSWD) send_user_reset_email(request, user.email, INIT_PASSWD)
msg = _('Successfully resetted password to %(passwd)s, an email has been sent to %(user)s.') % \
{'passwd': INIT_PASSWD, 'user': user.email}
messages.success(request, msg)
except Exception, e:
logger.error(str(e))
msg = _('Successfully resetted password to %(passwd)s, but failed to send email to %(user)s, please check your email configuration.') % \
{'passwd':INIT_PASSWD, 'user': user.email}
messages.success(request, msg)
else: else:
messages.success(request, _(u'Successfully resetting password to %s') % INIT_PASSWD) messages.success(request, _(u'Successfully resetted password to %(passwd)s for user %(user)s.') % \
{'passwd':INIT_PASSWD,'user': user.email})
else:
messages.success(request, _(u'Successfully resetted password to %(passwd)s for user %(user)s. But email notification can not be sent, because Email service is not properly configured.') % \
{'passwd':INIT_PASSWD,'user': user.email})
except User.DoesNotExist: except User.DoesNotExist:
msg = _(u'Failed to reset password: user does not exist') msg = _(u'Failed to reset password: user does not exist')
messages.error(request, msg) messages.error(request, msg)
@@ -2033,12 +2044,8 @@ def send_user_add_mail(request, email, password):
'protocol': use_https and 'https' or 'http', 'protocol': use_https and 'https' or 'http',
'site_name': settings.SITE_NAME, 'site_name': settings.SITE_NAME,
} }
try:
send_mail(_(u'Seafile Registration Information'), t.render(Context(c)), send_mail(_(u'Seafile Registration Information'), t.render(Context(c)),
None, [email], fail_silently=False) None, [email], fail_silently=False)
messages.success(request, _(u'Successfully sending mail'))
except:
messages.error(request, _(u'Failed to send mail'))
@login_required @login_required
def user_add(request): def user_add(request):
@@ -2055,8 +2062,7 @@ def user_add(request):
email = form.cleaned_data['email'] email = form.cleaned_data['email']
password = form.cleaned_data['password1'] password = form.cleaned_data['password1']
user = User.objects.create_user(email, password, user = User.objects.create_user(email, password, is_staff=False,
is_staff=False,
is_active=True) is_active=True)
if request.user.org: if request.user.org:
@@ -2069,8 +2075,18 @@ def user_add(request):
return HttpResponseRedirect(reverse('org_useradmin', return HttpResponseRedirect(reverse('org_useradmin',
args=[url_prefix])) args=[url_prefix]))
else: else:
if hasattr(settings, 'EMAIL_HOST'): if IS_EMAIL_CONFIGURED:
if SEND_EMAIL_ON_ADDING_SYSTEM_MEMBER:
try:
send_user_add_mail(request, email, password) send_user_add_mail(request, email, password)
messages.success(request, _(u'Successfully added user %s. An email notification has been sent.' % email))
except Exception, e:
logger.error(str(e))
messages.success(request, _(u'Successfully added user %s. An error accurs when sending email notification, please check your email configuration.' % email))
else:
messages.success(request, _(u'Successfully added user %s.' % email))
else:
messages.success(request, _(u'Successfully added user %s. But email notification can not be sent, because Email service is not properly configured.' % email))
return HttpResponseRedirect(reverse('sys_useradmin', args=[])) return HttpResponseRedirect(reverse('sys_useradmin', args=[]))
else: else: