Search code examples
pythondjangosendgriddjango-settings

Sending emails from my django website, via sendgrid


I want to send account confirmation emails to all the users who sign up on my website, so it has to be an HTML email with the activation link. This is how i am trying to do it:

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

When this particular view is rendered, it throws the following error message:

'UnauthorizedError' object has no attribute 'message'

Since this doesn't send the emails via an SMTP server, according to my understanding i don't need to add anything to my settings.py file(i did add 'sendgrid' to my installed apps after i installed it using pip)Can someone please point out what i did wrong? I have been stuck on this for a while now...

Thank you for your time


Solution

  • I think this line is causing an error.

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

    Whatever exception is occuring, it doens't have message property.

    Two solutions.

    1. print(e)

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