我正在尝试从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
在docker外部发送电子邮件没有问题。
我尝试了Google troubleshooting steps的每一步。目前,我有适用于本地应用程序的两步验证,但仍不适用于docker one。
我不一定需要Google SMTP(我在那里有一个帐户),但是我要实现的是在注册Django应用程序后向用户发送带有激活链接的电子邮件。
我尝试不使用2因子身份验证-结果相同。我在网络服务中的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
发送电子邮件的代码(在docker外部工作):
def email(request):
mail_subject = 'Activate your account'
message = 'test'
to_email = 'example@example.com'
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return redirect('index')
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'example@example.com'
EMAIL_HOST_PASSWORD = '***'
EMAIL_PORT = 587
答案 0 :(得分: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')
我仍然想知道这是否是从Django设置传递变量的正确方法。我是用优雅的方式做吗,有必要吗?这是smtp的最佳方法吗?
答案 1 :(得分:0)