pri*_*rib 6 python django sendgrid
我正在尝试使用 Sendgrid 从 Django 应用程序发送电子邮件。我尝试了很多配置,但我的Gmail帐户仍然没有收到任何电子邮件。您可以在下面看到我的配置:
设置.py:
SEND_GRID_API_KEY = 'APIGENERATEDONSENDGRID'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'mySENDGRIDusername'
EMAIL_HOST_PASSWORD = 'myEMAILpassword' #sendgrid email
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'MYEMAIL' #sendgrig email
Run Code Online (Sandbox Code Playgroud)
视图.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import ContactForm
from django.core.mail import send_mail
from django.conf import settings
from django.template.loader import get_template
def index(request):
return render(request, 'index.html')
def contact(request):
success = False
form = ContactForm(request.POST)
if request.method == 'POST':
name = request.POST.get("name")
email = request.POST.get("email")
message = request.POST.get("message")
subject = 'Contact from MYSITE'
from_email = settings.DEFAULT_FROM_EMAIL
to_email = [settings.DEFAULT_FROM_EMAIL]
message = 'Name: {0}\nEmail:{1}\n{2}'.format(name, email, message)
send_mail(subject, message, from_email, to_email, fail_silently=True)
success = True
else:
form = ContactForm()
context = {
'form': form,
'success': success
}
return render(request, 'contact.html',context)
Run Code Online (Sandbox Code Playgroud)
你们知道会发生什么吗?我在本地可以收到邮件,在终端也可以看到,但是根本发不出邮件。
在尝试使用 SMTP 设置 Django 的 sendgrid 时,我有点挣扎。对我有用的是以下内容:
设置.py
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey'
EMAIL_HOST_PASSWORD = 'sendgrid-api-key' # this is your API key
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = 'your-email@example.com' # this is the sendgrid email
Run Code Online (Sandbox Code Playgroud)
我使用了这个配置,运行正常,强烈建议使用环境变量来填充EMAIL_HOST_PASSWORD
and DEFAULT_FROM_EMAIL
,所以代码如下:
import os # this should be at the top of the file
# ...
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", "")
Run Code Online (Sandbox Code Playgroud)
然后,在发送电子邮件时,我使用了以下代码:
from django.conf import settings
from django.core.mail import send_mail
send_mail('This is the title of the email',
'This is the message you want to send',
settings.DEFAULT_FROM_EMAIL,
[
settings.EMAIL_HOST_USER, # add more emails to this list of you want to
]
)
Run Code Online (Sandbox Code Playgroud)