SMTPAuthenticationError - 535,b'5.7.8 不接受用户名和密码。- 从docker发送电子邮件

Mic*_*acz 5 python email django smtp docker

我正在尝试从 Ubuntu 上 docker 中的 django 应用程序发送电子邮件,并且收到以下消息:

Request Method: GET
Request URL:    https://localhost:8001/accounts/mail/
Django Version: 2.2.5
Exception Type: SMTPAuthenticationError
Exception Value:    
(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials x76sm1225174ljb.81 - gsmtp')
Exception Location: /usr/local/lib/python3.7/smtplib.py in auth, line 642
Python Executable:  /usr/local/bin/python
Python Version: 3.7.4
Run Code Online (Sandbox Code Playgroud)

在docker外发送邮件是没有问题的。

我尝试了Google 故障排除步骤中的每一步。目前我有两步验证,适用于本地应用程序,但仍然不适用于 docker one。

我不一定需要 Google SMTP(我在那里有一个帐户),但我要实现的是在注册 django 应用程序后向用户发送带有激活链接的电子邮件。

我在没有双因素身份验证的情况下尝试过 - 结果相同。我在 Web 服务中的 docker-compose 设置:

services:
  web:
    build: ./app
    command: python manage.py runsslserver 0.0.0.0:8001
    stdin_open: true
    tty: true
    volumes:
      - ./app/:/usr/src/app/
      - /etc/localtime:/etc/localtime
      - /etc/timezone:/etc/timezone
    ports:
      - 8001:8001
      - 587:587
      - 25:25
      - 465:465
Run Code Online (Sandbox Code Playgroud)

以及发送电子邮件的代码(在泊坞窗之外工作):

Request Method: GET
Request URL:    https://localhost:8001/accounts/mail/
Django Version: 2.2.5
Exception Type: SMTPAuthenticationError
Exception Value:    
(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials x76sm1225174ljb.81 - gsmtp')
Exception Location: /usr/local/lib/python3.7/smtplib.py in auth, line 642
Python Executable:  /usr/local/bin/python
Python Version: 3.7.4
Run Code Online (Sandbox Code Playgroud)

设置.py

services:
  web:
    build: ./app
    command: python manage.py runsslserver 0.0.0.0:8001
    stdin_open: true
    tty: true
    volumes:
      - ./app/:/usr/src/app/
      - /etc/localtime:/etc/localtime
      - /etc/timezone:/etc/timezone
    ports:
      - 8001:8001
      - 587:587
      - 25:25
      - 465:465
Run Code Online (Sandbox Code Playgroud)

Mic*_*acz 1

问题解决了!我已经应用了不同的代码来发送电子邮件。

import smtplib
import ssl

def email(request):
    port = settings.EMAIL_PORT
    smtp_server = settings.EMAIL_HOST
    sender_email = settings.EMAIL_HOST_USER
    password = settings.EMAIL_HOST_PASSWORD
    receiver_email = 'example@example.com'
    subject = 'Website registration'
    body = 'Activate your account.'
    message = 'Subject: {}\n\n{}'.format(subject, body)
    context = ssl.create_default_context()
    with smtplib.SMTP(smtp_server, port) as server:
        server.ehlo()  # Can be omitted
        server.starttls(context=context)
        server.ehlo()  # Can be omitted
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message)
    return redirect('index')
Run Code Online (Sandbox Code Playgroud)

我仍然想知道这是否是从 django 设置传递变量的正确方法。我这样做是否优雅并且有必要吗?这是 smtp 的最佳方式吗?