gpt4 book ai didi

python - 在 Django 中使用 Sendgrid 发送电子邮件

转载 作者:太空宇宙 更新时间:2023-11-03 15:45:16 24 4
gpt4 key购买 nike

我正在尝试使用 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

views.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)

你们知道会发生什么吗?我可以在本地获取电子邮件,并且可以在终端中看到它,但是根本无法发送电子邮件。

最佳答案

尝试使用 SMTP 通过 Django 设置 sendgrid 时,我遇到了一些困难。对我有用的是:

settings.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

我使用的是这个配置,可以正常使用,强烈建议使用环境变量填写EMAIL_HOST_PASSWORDDEFAULT_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", "")

然后,在发送电子邮件时我使用了以下代码:

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
]
)

关于python - 在 Django 中使用 Sendgrid 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50316675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com