Django SMTP Gmail не работает в производстве - PullRequest
0 голосов
/ 17 февраля 2020

Я использую django для отправки электронной почты через SMTP Gmail. Однако это работает только до развертывания. В производственном процессе или развертывании, как бы вы ни звонили, когда я пытаюсь отправить электронное письмо, оно постоянно загружается и выдает только «Ошибка сервера 500».

Ниже приведена часть моего 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 = config['EMAIL_USER']
EMAIL_HOST_PASSWORD = config['EMAIL_PASS']

Ниже .../django_project/users/views.py

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Your account has been created! You are now able to log in.')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})

@login_required()
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(request.POST,
                                   request.FILES,
                                   instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)

    context = {
        'u_form': u_form,
        'p_form': p_form
    }
    return render(request, 'users/profile.html', context)

Что сбивает с толку, так это то, что в моих обучающих видео нет ни одного из django.core.mail import send_mail или чего-то еще. Так что я не уверен, должен ли показываться приведенный выше файл view.py.

Возможно, эта проблема связана с самой Gmail. Пожалуйста, дайте мне знать, как я могу решить это. Спасибо.

РЕДАКТИРОВАНИЕ

Я кратко установил DEBUG = True и увидел сообщения об ошибках от error.log.

[Tue Feb 18 12:10:04.400741 2020] [core:notice] [pid 11826:tid 139852027644992] AH00094: Command line: '/usr/sbin/apache2'
[Tue Feb 18 12:15:05.589207 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984] Internal Server Error: /password-reset/
[Tue Feb 18 12:15:05.589265 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984] Traceback (most recent call last):
[Tue Feb 18 12:15:05.589270 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
[Tue Feb 18 12:15:05.589274 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     response = get_response(request)
[Tue Feb 18 12:15:05.589278 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
[Tue Feb 18 12:15:05.589282 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     response = self.process_exception_by_middleware(e, request)
[Tue Feb 18 12:15:05.589286 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
[Tue Feb 18 12:15:05.589290 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     response = wrapped_callback(request, *callback_args, **callback_kwargs)
[Tue Feb 18 12:15:05.589294 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
[Tue Feb 18 12:15:05.589298 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     return self.dispatch(request, *args, **kwargs)
[Tue Feb 18 12:15:05.589301 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
[Tue Feb 18 12:15:05.589305 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     return bound_method(*args, **kwargs)
[Tue Feb 18 12:15:05.589309 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
[Tue Feb 18 12:15:05.589313 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     response = view_func(request, *args, **kwargs)
[Tue Feb 18 12:15:05.589316 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/contrib/auth/views.py", line 222, in dispatch
[Tue Feb 18 12:15:05.589320 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     return super().dispatch(*args, **kwargs)
[Tue Feb 18 12:15:05.589324 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
[Tue Feb 18 12:15:05.589327 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     return handler(request, *args, **kwargs)
[Tue Feb 18 12:15:05.589331 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/views/generic/edit.py", line 142, in post
[Tue Feb 18 12:15:05.589335 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     return self.form_valid(form)
[Tue Feb 18 12:15:05.590890 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/contrib/auth/views.py", line 235, in form_valid
[Tue Feb 18 12:15:05.590901 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     form.save(**opts)
[Tue Feb 18 12:15:05.590905 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/contrib/auth/forms.py", line 324, in save
[Tue Feb 18 12:15:05.590909 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     user_email, html_email_template_name=html_email_template_name,
[Tue Feb 18 12:15:05.590913 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/contrib/auth/forms.py", line 272, in send_mail
[Tue Feb 18 12:15:05.590916 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     email_message.send()
[Tue Feb 18 12:15:05.590920 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/core/mail/message.py", line 276, in send
[Tue Feb 18 12:15:05.590923 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     return self.get_connection(fail_silently).send_messages([self])
[Tue Feb 18 12:15:05.590927 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages
[Tue Feb 18 12:15:05.590930 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     new_conn_created = self.open()
[Tue Feb 18 12:15:05.590934 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/home/djtu/django_project/venv/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 62, in open
[Tue Feb 18 12:15:05.590942 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     self.connection = self.connection_class(self.host, self.port, **connection_params)
[Tue Feb 18 12:15:05.590946 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/usr/lib/python3.7/smtplib.py", line 251, in __init__
[Tue Feb 18 12:15:05.590949 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     (code, msg) = self.connect(host, port)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
[Tue Feb 18 12:15:05.590953 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/usr/lib/python3.7/smtplib.py", line 336, in connect
[Tue Feb 18 12:15:05.590956 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     self.sock = self._get_socket(host, port, self.timeout)
[Tue Feb 18 12:15:05.590960 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/usr/lib/python3.7/smtplib.py", line 307, in _get_socket
[Tue Feb 18 12:15:05.590963 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     self.source_address)
[Tue Feb 18 12:15:05.590966 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/usr/lib/python3.7/socket.py", line 727, in create_connection
[Tue Feb 18 12:15:05.590970 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     raise err
[Tue Feb 18 12:15:05.590973 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]   File "/usr/lib/python3.7/socket.py", line 716, in create_connection
[Tue Feb 18 12:15:05.590976 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984]     sock.connect(sa)
[Tue Feb 18 12:15:05.590980 2020] [wsgi:error] [pid 11827:tid 139851910838016] [remote 121.131.97.11:49984] TimeoutError: [Errno 110] Connection timed out

Я надеюсь, что этот журнал даст некоторые разъяснения о том, что пошло не так. Кто-нибудь может указать мне правильное направление?

РЕДАКТИРОВАНИЕ # 2

Спасибо Сачину. Я попытался, как и предлагалось, но мой сервер не смог подключиться. Вместо этого он показывает эти сообщения.

(venv) myusername@hostname:~$ telnet smtp.gmail.com 587
Trying 2404:6800:4008:c00::6d...
Trying 108.177.97.109...
telnet: Unable to connect to remote host: Connection timed out

Тем не менее проблема остается, к сожалению.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...