I've been struggling for days trying to get SendGrid to send an email from a contact page on a website I'm building. First, it was SMTPServerDisconnected errors, and I think I fixed that now it's this SMTPSenderRefused Error.
settings.py
#Load environment variables from .env file
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
#Email for contact form
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
DEFAULT_FROM_EMAIL = '[email protected]'
SENDGRID_SANBOX_MODE_IN_DEBUG = False
views.py:
def contact(request: HttpRequest) -> HttpResponse:
if request.method == "GET":
form = ContactForm()
elif request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
name = bleach.clean(form.cleaned_data["name"])
email = bleach.clean(form.cleaned_data["email"])
subject = f'Message from {name} about {bleach.clean(form.cleaned_data["subject"])}'
message = bleach.clean(form.cleaned_data["message"])
recipients = [settings.DEFAULT_FROM_EMAIL]
try:
send_mail(subject, message, email, recipients, fail_silently=False)
except BadHeaderError:
return render(request, "contact.html", {"form": form, "success": False})
form = ContactForm()
return render(request, "contact.html", {"form": form, "success": True})
else:
raise NotImplementedError
return render(request, "contact.html", {"form": form})
I've switched between fail_silently=False
and fail_silently=True
, but when it's true the email doesn't send through anyways so I've just left it false for now.
Lastly, here is the traceback I got:
Environment:
Request Method: POST
Request URL: http://localhost:8000/contact/
Django Version: 4.0
Python Version: 3.9.12
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Blume_Website.apps.accounts',
'Blume_Website.apps.contact']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/Blume_Website/apps/contact/views.py", line 25, in contact
send_mail(subject, message, email, recipients, fail_silently=False)
File "/usr/local/lib/python3.9/site-packages/django/core/mail/__init__.py", line 61, in send_mail
return mail.send()
File "/usr/local/lib/python3.9/site-packages/django/core/mail/message.py", line 284, in send
return self.get_connection(fail_silently).send_messages([self])
File "/usr/local/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 109, in send_messages
sent = self._send(message)
File "/usr/local/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 125, in _send
self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
File "/usr/local/lib/python3.9/smtplib.py", line 887, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
Exception Type: SMTPSenderRefused at /contact/
Exception Value: (550, b'Unauthenticated senders not allowed', '[email protected]')
The "[email protected]" would be the person using the contact form, and I thought it was because it's a fake email but when I tried to use a real one, that also didn't work.
I've looked at numerous stack overflow pages, and watched a youtube video or two but had no luck. Not sure where the problem lies. Thank you for any help!
CodePudding user response:
The problem is that you're trying to use a From
address that you have not verified - specifically you're trying to use email
which is the email address submitted in the form. You can't do this - because it would allow you to send mail on behalf of anyone without their authorisation.
The from
address supplied to send_mail
must be an address that you have verified on Sendgrid, so you have to do:
# Note, 3rd argument has changed
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipients, fail_silently=False)
If you want to be able to reply to the email address that was submitted, you can set the reply_to
parameter on the message. You can't use the send_mail
helper to do this - instead you have to use the EmailMessage
class:
from django.core.mail import EmailMessage
email_message = EmailMessage(
subject,
message,
settings.DEFAULT_FROM_EMAIL,
recipients,
reply_to=[email],
)
email_message.send()