Giter VIP home page Giter VIP logo

django-sendgrid-v5's People

Contributors

alichass avatar blackfire70 avatar emadmokhtar avatar florimondmanca avatar jeremy-engel avatar josephabrahams avatar krishnamanohar1997 avatar kronion avatar liavkoren avatar lowlevel-1989 avatar mattfanto avatar michi88 avatar mick88 avatar mr-napik avatar ourcach avatar ptsteadman avatar sklarsa avatar sobolevn avatar tirkarthi avatar tomasgarzon avatar williano avatar wrparker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-sendgrid-v5's Issues

How to solve 401 Unauthorized issue ?

I tried to whitelist the ips, then tried to disable whitelisting from Sendgrid, but I keep getting this error when sending an email:

[ERROR] exception
HTTP Error 401: Unauthorized
{'reason': 'Unauthorized', 'body': b'{"errors":[{"message":"The requestor\'s IP Address is not whitelisted","field":null,"help":null}]}', 'headers': <http.client.HTTPMessage object at 0x7f6e8da4d898>, 'status_code': 401}

Any idea why that could be ?

sending email from django setup is not working

Running django localhost.
I have the following settings

EMAIL_BACKEND = "sendgrid_backend.SendgridBackend"
SENDGRID_API_KEY= os.environ.get('SENDGRID_API_KEY')
SENDGRID_SANDBOX_MODE_IN_DEBUG=False

send_mail('test Subject here', 'Here is the message.', 'from_email' , ['email_to_be_sent_to'], fail_silently=False)

nothing happens. No emails are sent. How can I debug this?

Integration

Hello, Thank you for publishing API integration source code.

But I have been wondering how to integrate it in my views.py file.

UnicodeDecodeError when encoding attachment in Python 2.7

I am getting an error:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)
  File "C:\Users\Mick\Desktop\Projects\django\meg-forms\lib\site-packages\django\core\mail\message.py", line 348, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:\Users\Mick\Desktop\Projects\django\meg-forms\lib\site-packages\sendgrid_backend\mail.py", line 63, in send_messages
    data = self._build_sg_mail(msg)
  File "C:\Users\Mick\Desktop\Projects\django\meg-forms\lib\site-packages\sendgrid_backend\mail.py", line 161, in _build_sg_mail
    content = content.encode()

Relevant code:

attachment.filename = filename
# todo: Read content if stream?
if isinstance(content, str):
    # line 161:
    content = content.encode()
attachment.content = base64.b64encode(content).decode()
attachment.type = mimetype

the attachment is an xls document and the first byte us 0xd0. This crashes sendgrid, because b'\xd0'.encode() produces an error. Ordinarily encode() encodes unicode into a byte string, but in the code above, it only executes for strings which are already bytestrings (Python 2.7) due to the condition, which makes no sense to me. Does it have anything to do with Python 3 compatibility?

Environment:
Python 2.7.9
django-sendgrid-v5==0.6.88
sendgrid==5.3.0

sending emails to multiple recipients not working

I just realize that whenever we send emails to a mailing list as follow:

        # settings.py
        MANAGERS = ['[email protected]', '[email protected]']

        # email.py
        from django.core.mail import send_mail
        from django.conf import settings

        result_managers = send_mail(manager_subject, message,
                                    from_email, settings.MANAGERS,
                                    html_message=manager_message,
                                    fail_silently=False)

only one of the recipients in the list will receive the email. By checking the last 3 days of activity on sendgrid, I see that 3/8th of mails went to [email protected] and 5/8th went to [email protected]. Assuming an email is picked randomly from the list :/

This is unfortunately a critical issue. Not sure if it's related to this project SendgridBackend or an issue with the upstream sendgrid service.

Any idea why this bug occurs and if it can be fixed quickly @sklarsa ?

missing release notes

project got updated to 0.7.0 6 days ago, but no git tag got created and no releases notes can be found.
What was this upgrade about ?

Thank you

Update Community libraries in Sendgrid Page

I saw this library on the official website a few months ago, and now it disappeared.
I would like to know why, Is there any reason?
I think it's the best place to be and get feedback.
Btw, the name should be like django-sendgrid-backend or something like that
just to not be tied to a special sendgrid-python version.

Anyway, thanks for your contribution.

commas in sender address names raise 400 error from sendgrid api

Just hit this issue in production today unfortunately using this library, haven't had time to delve into it properly but will send a PR if I get the time

Steps to reproduce:

from dango.core.mail import send_mail
send_mail( "Subject", "Message", "Sender, Some Org <[email protected]>", ["[email protected]"])

{'status_code': 400, 'reason': 'Bad Request', 'body': b'{"errors":[{"message":"The from object must be provided for every email send. It is an object that requires the email parameter, but may also contain a name parameter.  e.g. {\\"email\\" : \\"[email protected]\\"}  or {\\"email\\" : \\"[email protected]\\", \\"name\\" : \\"Example Recipient\\"}.","field":"from.email","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.from"}]}', 'headers': <http.client.HTTPMessage object at 0x7fa2885b6198>}

I guess there is some parsing issue when converting smtp from_email addresses to the sendgrid sender object format?

Add support for ganalytics UTM parameters

It'd be great if there was some kind of support for defining ganalytics settings.

I was thinking rather than defining a new SETTING object, you could grab the attribute on the EmailMessage if it exists.

Current method for providing settings:

tracking_settings = TrackingSettings()

Proposal:

msg = EmailMessage( .. )
msg.tracking_settings = TrackingSettings(
    open_tracking=OpenTracking(..),
    ganalytics=Ganalytics(..)
)

Then, in _build_sg_mail, you'd just check for the attribute and assign it:

mail.tracking_settings = getattr(msg, "tracking_settings", None)

What do you think?

If you wanted to loosely support most scenarios, you could consider something like getting all custom attributes added to EmailMessage (by diffing the attributes of the msg instance vs a fresh EmailMessage) and graft all extra attributes onto the Mail instance. I haven't thought too hard about this option though.

Error sending a csv file

When sending an CSV file as an attachment of the email, the following error is displayed:

``/home/ourcach/.virtualenvs/.../lib/python3.5/site-packages/sendgrid_backend/mail.py in _build_sg_mail(self, msg)
147 attachment.filename = filename
148 # todo: Read content if stream?
--> 149 attachment.content = base64.b64encode(content)
150 attachment.type = mimetype
151

/home/ourcach/.virtualenvs/.../lib/python3.5/base64.py in b64encode(s, altchars)
57 """
58 # Strip off the trailing newline
---> 59 encoded = binascii.b2a_base64(s)[:-1]
60 if altchars is not None:
61 assert len(altchars) == 2, repr(altchars)

TypeError: a bytes-like object is required, not 'str'``

` content = StringIO()
csv_writer = csv.writer(content)

csv_writer.writerow(["a", "b", "c", "d","e"])

msg = EmailMultiAlternatives(
    from_email=from_email, to=to_addresses, body="no HTML body"
)

msg.attach("file.csv", csv_writer.getValue(), "text/csv")
`

I tested this for csv only to correct the issue above, but i have a feeling that it may break other filetypes:
if isinstance(content, str): content = content.encode() attachment.content = base64.b64encode(content).decode() attachment.type = mimetype

Unique Arguments "custom_args" is not picked.

If you try to pass a unique argument "which called custom_args in sendgrid APIs" in the message, the Backend won't pick it and assign it to SendGrid APIs.

The solution is to check if there is custom args and them call the APIs to add them.

    def _build_sg_mail(self, msg):
        ...
        if msg.custom_args:
            for k, v in msg.custom_args.items():
                personalization.add_custom_arg(CustomArg(k, v))

Add TravisCI Caching

Cache the virtualenvs created by tox so we don't have to reinstall them every time we run tests

HTTPMessage object has no attribute getheader

In your recent commit 8a2eab4, you're trying to call getheader from an HTTPMessage object that doesn't have such attribute.

msg.extra_headers['message_id'] = resp.headers.getheader('x-message-id')

Django Version: 2.0.6
django-sendgrid-v5 version: 0.6.89

No problem with v0.6.88

Send_mail doesn't raise an exception or send emails

Hi,

As the title says, send_mail didn't send the emails, but there was no exception raised, and fail_siliently is set to its default value, which I believed is False.

I have the following settings in settings.py:

EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend'
SENDGRID_API_KEY = '********'
SENDGRID_SANDBOX_MODE_IN_DEBUG = False

The code used to send the emails is:

username = self.user.username
from_email = username + "@example.com"
recipient_list = [email1, email2, email3]
cc = ['[email protected]']
subject = "Approved registration"
body = ""

send_mail(subject, body, from_email, recipient_list)

I also tried using EmailMessage, but it didn't work too:

email = EmailMessage(subject, body, from_email, recipient_list, cc=cc)
email.send()

I'm quite sure the API key is correct, since I created a new full access API key and it still doesn't work.

Plain text emails from dynamic templates

Hi,

It might be not an issue of this library, however, I would like to post this information in case someone else would run into similar issues. Today we noticed that our HTML dynamic template emails were sent out as plain text. We correlated the issue with the recent change on the Sendgrid side.

Out fix was to set content type explicitly

email = EmailMessage(from_email=email_from, to=[to])
# <<<
email.content_subtype = 'html'
# >>>

email.dynamic_template_data = ...
email.send(fail_silently=False)

Thanks,
Hena

Sending JSON body to SendGrid

I have looked for an example of trying to send a JSON body to the SendGrid WebMail API using django-sendgrid-v5 but have had no luck. I am trying to leverage the dynamic template option which I can see was just added to be supported not long ago. I can also see the documentation on sendgrid-python v6 here but I don't see how this connect to django-sendgrid-v5.

Any help is greatly appreciated, and afterwards I'll be glad to throw some examples together and create a PR to contribute to the documentation.

Unable to replace keys in html template with values.

Hi,
I'm using this library and I'm able to send the template email successfully to the recepient, but the problem is I'm unable to replace the keys in my html template generated in sendgrid with my values as shown in below code snippet. Please let me know what I'm doing wrong or what is the way to do it.
Version Installed: django-sendgrid-v5==0.8.1

Thanks

reset_url = "Some link"
mail = EmailMultiAlternatives(
subject="Demo",
body="This is a simple text email body.",
from_email="",
to=[email],
)
#Trying to replace the key in template here
mail.subscriptions = {"%reset_token%": reset_url}
mail.attach_alternative(
"

This is a simple HTML email body

", "text/html"
)
# Add template
mail.template_id = 'template_id here'
mail.send()

Categories

How do I add categories to the email?

I tried something like this but no dice.

EmailMessage(subject=subject, body=message, from_email=sender, to=[recipient, ], headers={'categories': 'dev'})

Any thoughts?

Sandbox mode: "Invalid type. Expected: boolean, given: string."

Problem description

Hi,

I was using SendGrid and django-sendgrid-v5 to send email in a Django app. At some point, I stumbled upon a 400 Bad Request error:

{
  "errors": [
    {
      "message": "Invalid type. Expected: boolean, given: string.",
      "field": "mail_settings.sandbox_mode.enable",
      "help": "http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.mail_settings.sandbox_mode.enable"
    }
  ]
}

Obviously, the sandbox_mode was being given a str value instead of a bool. In this package's source code, this is how it is computed:

# sendgrid_backend/mail.py, SendgridBackend.__init__()
self.sandbox_mode = settings.DEBUG and sandbox_mode_in_debug

I noticed that (for some reason) I had set DEBUG to be the empty string, ''. After that, I unset the environment variable so that a default value would be used โ€” False (the boolean). Then, all went fine.

The reason why sandbox_mode was given a string value in this context is because '' and False and '' and True both result in '' (not False!) in Python โ€” so sandbox_mode was effectively the empty string. Note that this could have occurred for any value of DEBUG that is "false-y", such as 0 or None.

Suggestions

This was a rather confusing experience and it seems like something the library code should anticipate. I wanted to discuss how not to have this happen again.

I envision two possible fixes:

  1. Add a runtime check when assigning self.sandbox_mode to make sure that sandbox_mode is assigned a bool. If not, raise an AssertionError with a helpful message, like so:
assert isinstance(self.sandbox_mode, bool), 'Some helpful message about DEBUG and SENDGRID_SANDBOX_MODE_IN_DEBUG here'

This check would be made upon server start-up, so we'd be warned before the app attempts to send any email.

  1. Force the conversion of settings.DEBUG to a bool. After all, the problem here was that I was using a false-y value believing it would be treated as False. I would also argue that the same operation should be done on sandbox_mode_in_debug (which may be assigned the value of SENDGRID_SANDBOX_MODE_IN_DEBUG) to prevent any issue.
self.sandbox_mode = bool(settings.DEBUG) and bool(sandbox_mode_in_debug)

Either (or another) way, I would be happy to provide a PR for this. Glad to discuss further.

Sending fails with empty email subject.

I am using built-in Django PasswordResetView.
When using empty email subject in "password_reset_subject.txt" this is what happens.

https://docs.djangoproject.com/en/2.0/topics/auth/default/#django.contrib.auth.views.PasswordResetView

[29/Mar/2018 16:13:06] "GET /konto/odzyskiwanie/ HTTP/1.1" 200 454
Internal Server Error: /konto/odzyskiwanie/
Traceback (most recent call last):
  File "...lib\site-packages\django\core\handlers\exception.py", line 35, in inner
    response = get_response(request)
  File "...lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "...lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "...lib\site-packages\django\views\generic\base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "...lib\site-packages\braces\views\_access.py", line 128, in dispatch
    request, *args, **kwargs)
  File "...lib\site-packages\django\utils\decorators.py", line 62, in _wrapper
    return bound_func(*args, **kwargs)
  File "...lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "...lib\site-packages\django\utils\decorators.py", line 58, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "...lib\site-packages\django\contrib\auth\views.py", line 406, in dispatch
    return super().dispatch(*args, **kwargs)
  File "...lib\site-packages\django\views\generic\base.py", line 89, in dispatch
    return handler(request, *args, **kwargs)
  File "...lib\site-packages\django\views\generic\edit.py", line 142, in post
    return self.form_valid(form)
  File "...lib\site-packages\django\contrib\auth\views.py", line 419, in form_valid
    form.save(**opts)
  File "...lib\site-packages\django\contrib\auth\forms.py", line 297, in save
    email, html_email_template_name=html_email_template_name,
  File "...lib\site-packages\django\contrib\auth\forms.py", line 251, in send_mail
    email_message.send()
  File "...lib\site-packages\django\core\mail\message.py", line 294, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "...lib\site-packages\sendgrid_backend\mail.py", line 66, in send_messages
    self.sg.client.mail.send.post(request_body=data)
  File "...lib\site-packages\python_http_client\client.py", line 227, in http_request
    return Response(self._make_request(opener, request))
  File "...lib\site-packages\python_http_client\client.py", line 161, in _make_request
    raise exc
python_http_client.exceptions.BadRequestsError: HTTP Error 400: Bad Request
[29/Mar/2018 16:13:08] "POST /konto/odzyskiwanie/ HTTP/1.1" 500 171542

Duplicate emails in recipient_list raises exception and crashes

If I put the same email address twice in the recipient_list list the system will crash.

Why would I do that? Well, I'm "CC'ing" a central email address when any emails are sent from my Django server. It just happened that one of the users has the same email address as this central email address.

A simple "if x_email == y_email" statement fixes it on my end but I would imagine it should be fixed internally.

Traceback:
Traceback (most recent call last):
File "/home/daxm/PycharmProjects/SHP_Twilio_Phone_System/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/daxm/PycharmProjects/SHP_Twilio_Phone_System/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/daxm/PycharmProjects/SHP_Twilio_Phone_System/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/daxm/PycharmProjects/SHP_Twilio_Phone_System/IVR/views.py", line 116, in send_email
send_mail(
File "/home/daxm/PycharmProjects/SHP_Twilio_Phone_System/venv/lib/python3.8/site-packages/django/core/mail/init.py", line 61, in send_mail
return mail.send()
File "/home/daxm/PycharmProjects/SHP_Twilio_Phone_System/venv/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/daxm/PycharmProjects/SHP_Twilio_Phone_System/venv/lib/python3.8/site-packages/sendgrid_backend/mail.py", line 129, in send_messages
resp = self.sg.client.mail.send.post(request_body=data)
File "/home/daxm/PycharmProjects/SHP_Twilio_Phone_System/venv/lib/python3.8/site-packages/python_http_client/client.py", line 277, in http_request
self._make_request(opener, request, timeout=timeout)
File "/home/daxm/PycharmProjects/SHP_Twilio_Phone_System/venv/lib/python3.8/site-packages/python_http_client/client.py", line 184, in _make_request
raise exc

Cancel ganalytics tracking in links

Is there a way to cancel the ganalytics tracking in my links from settings :
all the links sent in emails are being added with this line:

?utm_medium=email&utm_campaign=website&utm_source=sendgrid.com&utm_source=sendgrid.com&utm_medium=email&utm_campaign=website

is there any way to cancel this or hide it?
thank you very much for your help

Compatibility with django lazy-translated strings

Related issue in a similar module: elbuo8/sendgrid-django#66

When we include lazily translated strings in an email message we get errors like:

/usr/local/lib/python3.6/site-packages/sendgrid_backend/mail.py in send_messages(self, email_messages)
     64
     65             try:
---> 66                 self.sg.client.mail.send.post(request_body=data)
     67                 success += 1
     68             except HTTPError:

/usr/local/lib/python3.6/site-packages/python_http_client/client.py in http_request(*_, **kwargs)
    215                             data = json.dumps(kwargs['request_body']).encode('utf-8')
    216                     else:
--> 217                         data = json.dumps(kwargs['request_body']).encode('utf-8')
    218                 params = kwargs['query_params'] if 'query_params' in kwargs else None
    219                 opener = urllib.build_opener()

/usr/local/lib/python3.6/json/__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    229         cls is None and indent is None and separators is None and
    230         default is None and not sort_keys and not kw):
--> 231         return _default_encoder.encode(obj)
    232     if cls is None:
    233         cls = JSONEncoder

/usr/local/lib/python3.6/json/encoder.py in encode(self, o)
    197         # exceptions aren't as detailed.  The list call should be roughly
    198         # equivalent to the PySequence_Fast that ''.join() would do.
--> 199         chunks = self.iterencode(o, _one_shot=True)
    200         if not isinstance(chunks, (list, tuple)):
    201             chunks = list(chunks)

/usr/local/lib/python3.6/json/encoder.py in iterencode(self, o, _one_shot)
    255                 self.key_separator, self.item_separator, self.sort_keys,
    256                 self.skipkeys, _one_shot)
--> 257         return _iterencode(o, 0)
    258
    259 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

/usr/local/lib/python3.6/json/encoder.py in default(self, o)
    178         """
    179         raise TypeError("Object of type '%s' is not JSON serializable" %
--> 180                         o.__class__.__name__)
    181
    182     def encode(self, o):

django-allauth compatibility

So, I can send via manage.py with the following

from django.core.mail import send_mail

send_mail(
    'Subject here',
    'Here is the message.',
    '[email protected]',
    ['[email protected]'],
    fail_silently=False,
)

but I am not getting emails that would be sent from django-allauth.
Any ideas? I'm it implements the standard send mail.

Email fails when using django-allauth

I'm working on getting SendGrid going and am having trouble with a 403 error when sending the Django user creation confirmation emails through SendGrid.

  • I'm running Django in debug mode on my local machine in a Docker container. I'm using the SendGrid Web API and not SMTP.
  • My API key is set for "Full Access."
  • I'm using SendGrid domain verification which it says is verified.
  • Sending email to the console by setting EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' works fine. I see the confirmation emails there.
  • The test mail from the python console as given in the Sending Emails with Django using SendGrid in 3 easy steps article works just as shown.

Here's what I have in my settings:

# settings.py
# SendGrid configuration
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend'
SENDGRID_API_KEY = os.environ.get("SENDGRID_API_KEY")
SENDGRID_SANDBOX_MODE_IN_DEBUG=False
SENDGRID_ECHO_TO_STDOUT=True

Here's the error I'm getting after submitting the signup form that's part of the django-allauth package:

Environment:
Request Method: POST
Request URL: http://localhost:8000/accounts/signup/

Django Version: 3.0.5
Python Version: 3.7.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'whitenoise.runserver_nostatic',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'django.contrib.humanize',
 'fontawesome_5',
 'sorl.thumbnail',
 'django_instagram',
 'allauth',
 'allauth.account',
 'crispy_forms',
 'debug_toolbar',
 'storages',
 'widget_tweaks',
 'bootstrap_modal_forms',
 'rules.apps.AutodiscoverRulesConfig',
 'hitcount',
 'sendgrid',
 'progear.apps.ProgearConfig',
 'users.apps.UsersConfig']
Installed Middleware:
['debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.middleware.cache.UpdateCacheMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 '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.7/site-packages/python_http_client/client.py", line 174, in _make_request
    return opener.open(request, timeout=timeout)
  File "/usr/local/lib/python3.7/urllib/request.py", line 531, in open
    response = meth(req, response)
  File "/usr/local/lib/python3.7/urllib/request.py", line 641, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/local/lib/python3.7/urllib/request.py", line 569, in error
    return self._call_chain(*args)
  File "/usr/local/lib/python3.7/urllib/request.py", line 503, in _call_chain
    result = func(*args)
  File "/usr/local/lib/python3.7/urllib/request.py", line 649, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)

During handling of the above exception (HTTP Error 403: Forbidden), another exception occurred:
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper
    return view(request, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/allauth/account/views.py", line 215, in dispatch
    return super(SignupView, self).dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/allauth/account/views.py", line 81, in dispatch
    **kwargs)
  File "/usr/local/lib/python3.7/site-packages/allauth/account/views.py", line 193, in dispatch
    **kwargs)
  File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/allauth/account/views.py", line 104, in post
    response = self.form_valid(form)
  File "/usr/local/lib/python3.7/site-packages/allauth/account/views.py", line 236, in form_valid
    self.get_success_url())
  File "/usr/local/lib/python3.7/site-packages/allauth/account/utils.py", line 192, in complete_signup
    signal_kwargs=signal_kwargs)
  File "/usr/local/lib/python3.7/site-packages/allauth/account/utils.py", line 152, in perform_login
    send_email_confirmation(request, user, signup=signup)
  File "/usr/local/lib/python3.7/site-packages/allauth/account/utils.py", line 323, in send_email_confirmation
    signup=signup)
  File "/usr/local/lib/python3.7/site-packages/allauth/account/models.py", line 58, in send_confirmation
    confirmation.send(request, signup=signup)
  File "/usr/local/lib/python3.7/site-packages/allauth/account/models.py", line 163, in send
    get_adapter(request).send_confirmation_mail(request, self, signup)
  File "/usr/local/lib/python3.7/site-packages/allauth/account/adapter.py", line 450, in send_confirmation_mail
    ctx)
  File "/usr/local/lib/python3.7/site-packages/allauth/account/adapter.py", line 137, in send_mail
    msg.send()
  File "/usr/local/lib/python3.7/site-packages/django/core/mail/message.py", line 276, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/usr/local/lib/python3.7/site-packages/sendgrid_backend/mail.py", line 122, in send_messages
    resp = self.sg.client.mail.send.post(request_body=data)
  File "/usr/local/lib/python3.7/site-packages/python_http_client/client.py", line 262, in http_request
    self._make_request(opener, request, timeout=timeout)
  File "/usr/local/lib/python3.7/site-packages/python_http_client/client.py", line 178, in _make_request
    raise exc

Exception Type: ForbiddenError at /accounts/signup/
Exception Value: HTTP Error 403: Forbidden

If I turn off debug mode, I get a server error:
"POST /accounts/signup/ HTTP/1.1" 500 145

I'm not even sure that this is related to the SendGrid integration, but when I bypass it, everything seems to work fine.

Any ideas what's going on?

Specify Sendgrid template

Hello,
is there any way to use a specific sendgrid template, either on settings.py or in the views.

Something like what is provided in the official Sendgrid package,

# Turn on the template option
message.add_filter('templates', 'enable', '1')

# Tell SendGrid which template to use
message.add_filter('templates', 'template_id', 'TEMPLATE-ALPHA-NUMERIC-ID')

source

Does not include both text/plain and text/html versions.

After upgrading from sendgrid-django, our emails used to be multipart/alternative with both text/plain and text/html content included, but are now simply text/html -- the plain text version is no longer included.

In sendgrid-django, an email that inherited from EmailMultiAlternatives would trigger both mail.add_content(Content("text/plain", email.body)) and mail.add_content(Content(alt[1], alt[0])). It appears that in django-sendgrid-v5, the same email only triggers mail.add_content(Content(alt[1], alt[0])) without adding the text/plain content.

The relevant diff seems to be https://github.com/elbuo8/sendgrid-django/blob/master/sgbackend/mail.py#L87-L91 vs https://github.com/sklarsa/django-sendgrid-v5/blob/master/sendgrid_backend/mail.py#L136-L144.

Is this an intentional change? My understanding of Django mail implies that a message with both message and html_message args should include both content types.

utf-8 encoding

When I send an html email using this API, the receiver got email in iso-8859-1 charset
and if I send email with simple SMTP with my gmail credentials, the receiver got email in utf-8 charset

can anyone help to send html email using utf-8 charset

The problem I face with iso-8859-1 encoding is that if the receiver is gmail user then gmail will append this in every email of the receiver
[Message clipped] View entire message

getheader() deprecated in Python 3

#32 aimed at fixing an issue with one of the returned responses using getheader(), however I ran into the same issue as @ryosuke-kubota. When an attribute error is thrown like that, it usually means a method is missing. I did some further investigation, because I tried to run sendemail() in my django install and failed.

Django v2.0.6
python v3.6.5

It turns out that getheader() is deprecated in python3. Since this library says that it supports Python 3.6.5, we should make a change. I an opening up a PR now to address this.

For reference:
Another project had a similar issue: wialon/python-wialon#8

Content-ID extra angle brackets for inline images

Hey, think there's an issue with inline images and the Content-ID tag. When using the default Django mailer, I can attach an image like this and all is well:

        with open(attachment_path, "rb") as image_file:
            msg_img = MIMEImage(image_file.read())
            msg_img.add_header('Content-ID', '<{}>'.format(filename))
            msg.attach(msg_img)

The message comes through with inline images, and the Content-ID tag set appropriately, like:

Content-Type: image/jpeg
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-ID: <myinlineimage.jpg>

When I do the same thing with this lib, those Content-ID angle brackets are doubled up, like:

Content-Disposition: inline; filename="part-1348a3fe9ce14c1da8c64b0eda3ad104.jpe"
Content-ID: <<myinlineimage.jpg>>
Content-Transfer-Encoding: base64
Content-Type: image/jpeg; name="part-1348a3fe9ce14c1da8c64b0eda3ad104.jpe"

That doesn't render, since it's not the correct format, and the images are just attachments instead of inline. I'm guessing the underlying sendgrid lib is the one adding the extra angle bracket, so to maintain API compatibility with Django's default mailer this lib probably has to strip existing brackets on the attachment?

Emailing from docker

Hi

This package works fine for me outside of docker. But I have a container, a celery worker, that will not send the mail. The container however can make HTTP requests. Am I right in thinking that if I have SENDGRID_API_KEY set this package is just making a HTTP request to the SendGrid API ? If this is true does anybody have any ideas why the mail doesn't work from this container but a standard HTTP request does, to say, Google's server ? I'm at a loss as to how to even corner the real issue on this one.

The to email parametre is required

sending emails as follow:

            result = send_mail(subject, message, from_email, emails,
                               html_message=html_message,
                               fail_silently=False)

from_email being a single email string, emails being a list of emails.

The server fails to send the mail with following error:

HTTP Error 400: Bad Request
b'{"errors":[{"message":"The to email parameter is required.","field":"personalizations.0.to.0.email","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.to"}]}'

Have you seen this before ?

Everything works fine but mails don't get delivered

I'm using this package to send mails in django. Everything works fine but the mail never reaches to the inbox, neither spam. I've also tried to look for a similar issue on the closed ones but nothing helpful
Here are my current configurations:
.env file:

EMAIL_BACKEND='sendgrid_backend.SendgridBackend' SENDGRID_API_KEY='SG.the_rest_of_the_api_key'

settings.py file:

EMAIL_BACKEND = env('EMAIL_BACKEND')
SENDGRID_API_KEY = env('SENDGRID_API_KEY')
SENDGRID_SANDBOX_MODE_IN_DEBUG=False

and my mail function:
from django.core.mail import send_mail

send_mail( mail_subject, message, '[email protected]', [to_email], fail_silently=False, )

On sending the email, I get no error, but still the mail doesn't get delivered.
What could I be missing?

HTTP Error 400 Bad Request - how to debug?

So I might be missing something here, but trying to send an email which appears to be well-formatted returns a generic 400 error. There is no indication why or how the email send actually failed. Looking in the SendGrid logs is no help; they show no attempt was made to send at all.

Reverting to the plain-old SMTP server backend sends it off without issue. So I have no idea what went wrong or how to fix. thoughts?

Per-email click tracking settings possible?

Sendgrid allows per-email settings AKA "filters", for example to configure click-tracking

The changes introduced in 7b1a291 take an "all or nothing" approach - based on Django settings, either all emails are tracked, or none of them.

However, a developer may need to enable tracking for some emails and disable it for others. For example, an email notification about a new blog post could use tracking to measure interaction, but a "password reset" email should never have the reset link rewritten.

Message-specific tracking settings could normally be configured by passing the headers kwarg to the EmailMessage constructor, for example like so:

smtp_headers = {
    "filters": {
    "clicktrack": {
        "settings": {
                "enable": "0"
            }
        },
        "opentrack": {
            "settings": {
                "enable": "0"
            }
        }
    }
}

EmailMessage(
    subject,
    plain_text_body,
    from_email,
    recipient,
    headers={
        'X-SMTPAPI': json.dumps(smtp_headers)
    }
)

As far as I can tell, at the moment the library ignores any custom headers passed via the headers kwarg of EmailMessage,__init__. Tracking settings are controlled entirely by the application's settings module:

track_email = True
if hasattr(settings, "SENDGRID_TRACK_EMAIL_OPENS"):
    track_email = settings.SENDGRID_TRACK_EMAIL_OPENS
self.track_email = track_email

track_clicks_html = True
if hasattr(settings, "SENDGRID_TRACK_CLICKS_HTML"):
    track_clicks_html = settings.SENDGRID_TRACK_CLICKS_HTML

self.track_clicks_html = track_clicks_html

track_clicks_plain = True
if hasattr(settings, "SENDGRID_TRACK_CLICKS_PLAIN"):
    track_clicks_plain = settings.SENDGRID_TRACK_CLICKS_PLAIN

[...]

tracking_settings = TrackingSettings()
tracking_settings.open_tracking = OpenTracking(self.track_email)
tracking_settings.click_tracking = ClickTracking(self.track_clicks_html, self.track_clicks_plain)

mail.tracking_settings = tracking_settings

Am I missing something here? Is it actually possible to configure tracking settings at runtime, for each specific email, or is that not supported?

HTML emails

How do I use this to send emails with HTML in them? Right now the HTML is getting escaped.

SSL: CERTIFICATE_VERIFY_FAILED

I use Python 3.5 and newest available Django on Ubuntu 16.04 machine.

Any ideas?

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)

During handling of the above exception, another exception occurred:


    return opener.open(request)
  File "/usr/lib/python3.5/urllib/request.py", line 466, in open
    response = self._open(req, data)
  File "/usr/lib/python3.5/urllib/request.py", line 484, in _open
    '_open', req)
  File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.5/urllib/request.py", line 1297, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "/usr/lib/python3.5/urllib/request.py", line 1256, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)>

Sending mail works with send_mail command but not on password reset form - Invalid Header?

Hello, I added password reset functionality with the built in defaults in Django and got it to output emails to a file, but am unable to integrate it with SendGrid. I've tried using this API, my settings are as follows:

SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
EMAIL_BACKEND = "sendgrid_backend.SendGridBackend" 

I tested in shell with send_mail, and it worked.
But I tried testing the password reset email on my localhost and received this error -

ImproperlyConfigured at /password_reset/
                SENDGRID_API_KEY must be declared in settings.py

Confusing, as I do have it declared in settings.py. I instead set the variable directly instead of reading it from env, but then trying to password reset gave me a HTTP 403 Forbidden Error.

ponse Internal Server Error: /password_reset/
Traceback (most recent call last):
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/contrib/auth/views.py", line 222, in dispatch
    return super().dispatch(*args, **kwargs)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/views/generic/edit.py", line 142, in post
    return self.form_valid(form)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/contrib/auth/views.py", line 235, in form_valid
    form.save(**opts)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/contrib/auth/forms.py", line 324, in save
    user_email, html_email_template_name=html_email_template_name,
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/contrib/auth/forms.py", line 272, in send_mail
    email_message.send()
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/django/core/mail/message.py", line 276, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/sgbackend/mail.py", line 66, in send_messages
    self.sg.client.mail.send.post(request_body=mail)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/python_http_client/client.py", line 262, in http_request
    self._make_request(opener, request, timeout=timeout)
  File "/Users/alibharwani/Documents/projects/webapps/opendict/django-venv/lib/python3.7/site-packages/python_http_client/client.py", line 178, in _make_request
    raise exc
python_http_client.exceptions.ForbiddenError: HTTP Error 403: Forbidden

I thought it might have something to do with my authentication on SendGrid, as I had authenticated my website so it might work. Testing on my website however, I get this:

2020-08-16T23:24:18.060199+00:00 app[web.1]: 2020-08-16 23:24:18 [10] [ERROR] pathname=/app/.heroku/python/lib/python3.7/site-packages/django/utils/log.py lineno=228 funcname=log_response Internal Server Error: /password_reset/
2020-08-16T23:24:18.060234+00:00 app[web.1]: Traceback (most recent call last):
2020-08-16T23:24:18.060235+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
2020-08-16T23:24:18.060236+00:00 app[web.1]:     response = get_response(request)
2020-08-16T23:24:18.060236+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
2020-08-16T23:24:18.060237+00:00 app[web.1]:     response = self.process_exception_by_middleware(e, request)
2020-08-16T23:24:18.060237+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
2020-08-16T23:24:18.060238+00:00 app[web.1]:     response = wrapped_callback(request, *callback_args, **callback_kwargs)
2020-08-16T23:24:18.060238+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view
2020-08-16T23:24:18.060238+00:00 app[web.1]:     return self.dispatch(request, *args, **kwargs)
2020-08-16T23:24:18.060239+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
2020-08-16T23:24:18.060239+00:00 app[web.1]:     return bound_method(*args, **kwargs)
2020-08-16T23:24:18.060239+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
2020-08-16T23:24:18.060240+00:00 app[web.1]:     response = view_func(request, *args, **kwargs)
2020-08-16T23:24:18.060240+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/views.py", line 222, in dispatch
2020-08-16T23:24:18.060240+00:00 app[web.1]:     return super().dispatch(*args, **kwargs)
2020-08-16T23:24:18.060240+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch
2020-08-16T23:24:18.060240+00:00 app[web.1]:     return handler(request, *args, **kwargs)
2020-08-16T23:24:18.060240+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/views/generic/edit.py", line 142, in post
2020-08-16T23:24:18.060241+00:00 app[web.1]:     return self.form_valid(form)
2020-08-16T23:24:18.060241+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/views.py", line 235, in form_valid
2020-08-16T23:24:18.060241+00:00 app[web.1]:     form.save(**opts)
2020-08-16T23:24:18.060241+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/forms.py", line 324, in save
2020-08-16T23:24:18.060242+00:00 app[web.1]:     user_email, html_email_template_name=html_email_template_name,
2020-08-16T23:24:18.060242+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/forms.py", line 272, in send_mail
2020-08-16T23:24:18.060242+00:00 app[web.1]:     email_message.send()
2020-08-16T23:24:18.060242+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/django/core/mail/message.py", line 276, in send
2020-08-16T23:24:18.060243+00:00 app[web.1]:     return self.get_connection(fail_silently).send_messages([self])
2020-08-16T23:24:18.060243+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/sgbackend/mail.py", line 66, in send_messages
2020-08-16T23:24:18.060243+00:00 app[web.1]:     self.sg.client.mail.send.post(request_body=mail)
2020-08-16T23:24:18.060243+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/python_http_client/client.py", line 262, in http_request
2020-08-16T23:24:18.060243+00:00 app[web.1]:     self._make_request(opener, request, timeout=timeout)
2020-08-16T23:24:18.060244+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/python_http_client/client.py", line 174, in _make_request
2020-08-16T23:24:18.060244+00:00 app[web.1]:     return opener.open(request, timeout=timeout)
2020-08-16T23:24:18.060244+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/urllib/request.py", line 525, in open
2020-08-16T23:24:18.060244+00:00 app[web.1]:     response = self._open(req, data)
2020-08-16T23:24:18.060245+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/urllib/request.py", line 543, in _open
2020-08-16T23:24:18.060245+00:00 app[web.1]:     '_open', req)
2020-08-16T23:24:18.060245+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/urllib/request.py", line 503, in _call_chain
2020-08-16T23:24:18.060245+00:00 app[web.1]:     result = func(*args)
2020-08-16T23:24:18.060245+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/urllib/request.py", line 1393, in https_open
2020-08-16T23:24:18.060246+00:00 app[web.1]:     context=self._context, check_hostname=self._check_hostname)
2020-08-16T23:24:18.060246+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/urllib/request.py", line 1350, in do_open
2020-08-16T23:24:18.060246+00:00 app[web.1]:     encode_chunked=req.has_header('Transfer-encoding'))
2020-08-16T23:24:18.060247+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/http/client.py", line 1262, in request
2020-08-16T23:24:18.060247+00:00 app[web.1]:     self._send_request(method, url, body, headers, encode_chunked)
2020-08-16T23:24:18.060247+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/http/client.py", line 1303, in _send_request
2020-08-16T23:24:18.060247+00:00 app[web.1]:     self.putheader(hdr, value)
2020-08-16T23:24:18.060248+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/http/client.py", line 1240, in putheader
2020-08-16T23:24:18.060248+00:00 app[web.1]:     raise ValueError('Invalid header value %r' % (values[i],))
2020-08-16T23:24:18.060248+00:00 app[web.1]: ValueError: Invalid header value b'Bearer <API_KEY>\n'

where <API_KEY> is my the value of my API Key.

Any help would be much appreciated, thank you

more info:

sendgrid==6.0.0
django-sendgrid-v5==0.8.1
Django==3.0.7

Not sending emails

I've been trying to write a simple view to send emails, but I keep getting 0 as result from send_mail

'''
Backend views
'''
from smtplib import SMTPException

from django.http import JsonResponse
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.conf import settings
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt


@require_POST
@csrf_exempt
def contact_email(request):
    '''
    Send an email to the user when he press the contact form
    '''
    email = request.POST.get('email')
    subject = 'Subject'
    message = ''  # Using html message instead
    html_message = render_to_string('email.html', {'email': email})
    from_email = settings.DEFAULT_FROM_EMAIL

    try:
        result = send_mail(subject, message, from_email, [email],
                  html_message=html_message,
                  fail_silently=False)
        if result == 0:
            return JsonResponse({
                'status': 'error',
                'errorMessage': 'Could not send email',
            }, status=400)
        return JsonResponse({
            'status': 'success'
        }, status=200)
    except SMTPException:
        return JsonResponse({
            'status': 'error',
            'errorMessage': 'Could not send email',
        }, status=400)

Might you have any idea as to why it happens, and how to debug this issue ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.