Отправка электронных писем с моего сайта django через sendgrid

Я хочу отправлять электронные письма с подтверждением учетной записи всем пользователям, которые зарегистрировались на моем сайте, поэтому это должно быть HTML письмо со ссылкой активации. Вот как я пытаюсь это сделать:

import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

def my_view(request):
            current_site = get_current_site(request)
            mail_subject = 'Welcome To IIITU Alumni Network'
            to_email = email
            ctx = {
                'user': user,
                'domain': current_site.domain,
                'uid':urlsafe_base64_encode(force_bytes(user.pk)),
                'token':account_activation_token.make_token(user),
            }
            message = Mail(
                to_emails = to_email,
                from_email = '<my email address>',
                subject = mail_subject,
                #I made this html page specifically for sending confirmation email
                #I am not sure if this is the correct way to do it
                html_content = render_to_string('network/email.html', ctx)
            )
            try:
                #I have this key as an environment variable
                sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
                #Now this is where the problem is
                response = sg.send(message)
                print(response.status_code)
                print(response.body)
                print(response.headers)
                return HttpResponse("A confirmation Email has been sent to your Institute email address. Please Confirm Your email to complete your registration")

            except Exception as e:
                print(e.message)
                return HttpResponse("The Server seems too busy!! Sorry for the inconvenience. Please try again later, or contact administrator if this problem persists.")

При отображении этого конкретного представления выдает следующее сообщение об ошибке:

У объекта 'UnauthorizedError' нет атрибута 'message'

Поскольку это не отправляет письма через SMTP-сервер, согласно моему пониманию, мне не нужно ничего добавлять в файл settings.py (я добавил 'sendgrid' в установленные приложения после того, как установил его с помощью pip) Может кто-нибудь указать, что я сделал неправильно? Я застрял на этом уже некоторое время...

Спасибо за ваше время

Я думаю, что эта строка вызывает ошибку.

    ...
except Exception as e:
    print(e.message)
    ...

Какое бы исключение не происходило, оно не имеет свойства message.

Два решения.

  1. print(e)

  2. remove try except block and try to figure out which exception is occurring and then catch that specifically.

Вернуться на верх