Coder Social home page Coder Social logo

django-amazon-ses's Introduction

django-amazon-ses

image

image

image

A Django email backend that uses Boto 3 to interact with Amazon Simple Email Service (SES).

Table of Contents

Installation

First, install the Django Amazon SES email backend:

$ pip install django-amazon-ses

Next, ensure that your Amazon Web Services (AWS) API credentials are setup, or that you are running on an Amazon EC2 instance with an instance profile that has access to the Amazon SES service.

AWS Credential Setup

AWS Named Profile

Create an AWS API credential profile named test using the AWS CLI:

$ aws --profile test configure

Ensure that the AWS_PROFILE environment variable is set so that Boto 3 knows which credentials profile to use:

$ AWS_PROFILE="test" gunicorn my:app

AWS EC2 Instance Profile

Create an instance profile with at least the ses:SendRawEmail action. Then, associate it with the instance/s running your application. An example policy that enables access to the ses:SendRawEmail action is below:

{
   "Version": "2012-10-17",
   "Statement": [
      {
         "Effect": "Allow",
         "Action": ["ses:SendRawEmail"],
         "Resource":"*"
      }
   ]
}

Django Configuration

Lastly, override the EMAIL_BACKEND setting within your Django settings file:

EMAIL_BACKEND = 'django_amazon_ses.EmailBackend'

Optionally, you can set the AWS credentials. If unset, the backend will gracefully fall back to other Boto 3 credential providers.

AWS_ACCESS_KEY_ID = 'my_access_key...'
AWS_SECRET_ACCESS_KEY = 'my_secret...'

Optionally, you can set the AWS region to be used (default is 'us-east-1'):

AWS_DEFAULT_REGION = 'eu-west-1'

Alternatively, provide AWS credentials using the settings below. This is useful in situations where you want to use separate credentials to send emails via SES than you would for other AWS services.

AWS_SES_ACCESS_KEY_ID = 'my_access_key...'
AWS_SES_SECRET_ACCESS_KEY = 'my_secret...'
AWS_SES_REGION = 'us-west-2'

If you want to force the use of a SES configuration set you can set the option below. This is useful when you want to do more detailed tracking of your emails such as opens and clicks. You can see more details at: https://docs.aws.amazon.com/ses/latest/DeveloperGuide/using-configuration-sets.html.

AWS_SES_CONFIGURATION_SET_NAME = 'my_configuration_set'

Usage

Once the configuration above is complete, use send_email to send email messages with Amazon SES from within your application:

from django.core.mail import send_mail

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

Signals

Two signals are provided for the backend, pre_send and post_send. Both signals receive the message object being sent. The post_send signal also receives the Amazon SES message ID of the sent message.

pre_send

You can modify the email message on pre_send. For example, if you have a blacklist of email addresses that should never receive emails, you can filter them from the recipients:

from django.dispatch.dispatcher import receiver
from django_amazon_ses import pre_send

@receiver(pre_send)
def remove_blacklisted_emails(sender, message=None, **kwargs):
    blacklisted_emails = Blacklisted.objects.values_list('email', flat)
    message.to = [email for email in message.to if email not in blacklisted_emails]

If the pre_send receiver function ends up removing all of the recipients from the message, the email is not processed and the post_send signal is not sent.

post_send

Similarly, the post_send signal can be used to log messages sent by the system. This is useful if you want to log the subject line of a message that bounced or received a complaint.

from django.dispatch.dispatcher import receiver
from django.utils import timezone

from django_amazon_ses import post_send

@receiver(post_send)
def log_message(sender, message=None, message_id=None, **kwargs):
    SentMessage.objects.create(
        subject = message.subject,
        body = message.body,
        message_id = message_id,
        date_sent = timezone.now()
    )

Testing

The test suite execution process is managed by tox and takes care to mock out the Boto 3 interactions with Amazon's API, so there is no need for a valid set of credentials to execute it:

$ tox

django-amazon-ses's People

Contributors

bryanquigley avatar dependabot-preview[bot] avatar eriknaslund avatar francoisfreitag avatar frco9 avatar hectcastro avatar jdufresne avatar jordanreiter avatar jshwright avatar nbeuchat avatar nicolaschung avatar rbreslow avatar tnation14 avatar whyscream 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

Watchers

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

django-amazon-ses's Issues

Add support for Django 4.x

Hello from Republic of Korea.

FYI, I was using django version 3 and python 3.7 in my project and I just upgrade these versions to Django 4.0.1 & Python 3.9

after that, Whenever I use the email service that consists of the django-amazon-ses, it returns this error.

File "/Users/johnyoun/.local/share/virtualenvs/my-env/lib/python3.9/site-packages/django_amazon_ses.py", line 11, in <module> pre_send = Signal(providing_args=["message"]) TypeError: __init__() got an unexpected keyword argument 'providing_args'

It seems that Django 4.0 no longer has a providing_args argument in Signal class!

Could you check this?

Sending emails and receiving bounces/complaints clarification

Hi,

  1. Could you please elaborate on the process of sending an email and getting it's delivery/bounce/complaint status?

  2. When sending emails in bulk (i.e list of 50K subscribers), does it send the emails one by one? If so, what is the sending rate (~30 emails per sec)?

Thanks.

Handling SES Throttling?

I read through;

  • Previous issues
  • Pull requests
  • The code

And it doesn't look like the retrying or queuing is handled in case of SES throttling.

Am I correct regarding this?

Thanks!

Install issue with poetry

I was trying to install it with poetry but couldn't resolve the dependency in the last two days which seems a big mess. Please solve this asap. Thank you.

Need AssumeRole support

Hello.

I want to use AssumeRole to use SES from another AWS account.
Can I add something like AWS_SES_ROLE_ARN to the configuration?

Thank you.

Region should not default to us-east-1

When running in an ECS container, I would expect the package to inherit the AWS settings from the container instead of defaulting to us-east-1. I would rather not specify the region since the container knows where it is.

Uses AWS_ACCESS_KEY_ID and not AWS_SES_ACCESS_KEY_ID when both set

I am using two separate access keys in my project: one which has access to my media bucket and one which has access to SES.

When I have both keys set in my project, I get a traceback.

AWS_ACCESS_KEY_ID = config.get("s3_storage", "aws_access_key_id")
AWS_SECRET_ACCESS_KEY = config.get("s3_storage", "aws_secret_access_key")

# DJANGO SES
EMAIL_BACKEND = 'django_amazon_ses.EmailBackend'
AWS_DEFAULT_REGION = 'us-east-1'
AWS_SES_ACCESS_KEY_ID = config.get('ses', 'email_host_user')
AWS_SES_SECRET_ACCESS_KEY = config.get('ses', 'email_host_password')
AWS_SES_REGION = 'us-east-1'
EMAIL_HOST_USER = config.get('django', 'email_host_user')
SUPPORT_EMAIL = config.get('django', 'support_email')
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the SendRawEmail operation: User '{my_bucket_user_arn}' is not authorized to perform 'ses:SendRawEmail' on resource '{some_amazon_arn}:identity/[email protected]'
[14/Mar/2018 15:25:57] "POST /accounts/login/ HTTP/1.1" 500 136132

When I comment out

AWS_ACCESS_KEY_ID = config.get("s3_storage", "aws_access_key_id")
AWS_SECRET_ACCESS_KEY = config.get("s3_storage", "aws_secret_access_key")

everything works as expected.

I think this is happening because of the __init__ method in django_amazon_ses.py, which just uses AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when they are supplied instead of first checking for AWS_SES_ACCESS_KEY_ID and AWS_SES_SECRET_ACCESS_KEY.

 def __init__(self, fail_silently=False, **kwargs):
        """Creates a client for the Amazon SES API.

        Args:
            fail_silently: Flag that determines whether Amazon SES
                client errors should throw an exception.

        """
        super(EmailBackend, self).__init__(fail_silently=fail_silently)
        access_key_id = getattr(settings, 'AWS_ACCESS_KEY_ID', None)
        secret_access_key = getattr(settings, 'AWS_SECRET_ACCESS_KEY', None)
        region_name = getattr(settings, 'AWS_DEFAULT_REGION', 'us-east-1')
        self.conn = boto3.client(
            'ses',
            aws_access_key_id=access_key_id,
            aws_secret_access_key=secret_access_key,
            region_name=region_name,
        )

How do I make it use my SES_ACCESS_KEY instead of my regular ACCESS_KEY?

Need to update the signature version for authentication?

Got this email from AWS today.

Amazon Web Services currently supports Amazon SES API requests that are signed using Signature Version 3 and Signature Version 4 processes. Signature Version 4 further enhances the security around authentication and authorization of Amazon SES customers by using a signing key instead of your secret access key. To improve the security for our customers, beginning October 1, 2020, Amazon Signature Version 3 will be turned off (deprecated) in Amazon SES in favor of Signature Version 4.

Amazon SES customers who are still using Signature Version 3 must migrate to Signature Version 4 by September 30, 2020. After that, Amazon SES will only accept requests that are signed using Signature Version 4. For more information, see Signature Version 4 signing process [1].

What Happens if I Don't Make Updates?

Requests signed with Signature Version 3 that are made after September 30, 2020 will fail to authenticate with Amazon SES. Requesters will see errors stating that the request must be signed with Signature Version 4.

References:
[1] https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html

Will this be handled by boto3 or we'll have to make any change?

are all the django.core.mail methods supported by this application ?

I went through all the documentation.
There no chapter explaining the Django methods supported. Is that normal ?
Can I send mass mails ?
Is html_content supported ?
Can I include links and anchors in mail content ?
Is this example working ?

from django.core import mail
connection = mail.get_connection()

# Manually open the connection
connection.open()

# Construct an email message that uses the connection
email1 = mail.EmailMessage(
    'Hello',
    'Body goes here',
    '[email protected]',
    ['[email protected]'],
    connection=connection,
)
email1.send() # Send the email

# Construct two more messages
email2 = mail.EmailMessage(
    'Hello',
    'Body goes here',
    '[email protected]',
    ['[email protected]'],
)
email3 = mail.EmailMessage(
    'Hello',
    'Body goes here',
    '[email protected]',
    ['[email protected]'],
)

# Send the two emails in a single call -
connection.send_messages([email2, email3])
# The connection was already open so send_messages() doesn't close it.
# We need to manually close the connection.
connection.close()

And can I do this ?

if html_message:
            email.content_subtype = 'html'
email.send()

Django cant find "ModuleNotFoundError: No module named 'django_amazon_ses'" in no debug mode.

Hi,

first of all, great module! Does alot of good work.

Im am currently having an problem where when i run the code on my server in production mode does django not find "django_amazon_ses" in "EMAIL_BACKEND" but i am able to work with the module in non production flawless.

38bb62366f7ef27686d847aa00771dc9

Where implement the code:
4dc14dab6c70655d37a825bb31c35d74

The thing is that when i run locally in production am I able to run the function but when I run it on the server does it not find the module.

Is there any solution on this problem?

Dear,
Emil

Migrate from Travis CI to GitHub Actions

Replace the existing Travis CI configuration with one based on GitHub Actions. Ensure that:

  • Matrix builds are preserved
  • Caches are setup appropriately
  • Tagged releases are automatically published to pypi

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.