Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to programmatically create message? #114

Open
thomastruett opened this issue Jun 25, 2018 · 1 comment
Open

Ability to programmatically create message? #114

thomastruett opened this issue Jun 25, 2018 · 1 comment

Comments

@thomastruett
Copy link

Am I missing this by chance? I would love this feature.

@andytwoods
Copy link

andytwoods commented Jun 25, 2018

I use the below to bulk send messages. Afraid you'll need to tease apart messages and email-messages. You could reciprocate the favour by augmenting the docs :)

def email_and_message_users(messages):
    message_list = []

    user_ids = []
    for message in messages:
        user_ids.append(message['recipient_user_id'])

    users = {}
    for user in User.objects.filter(id__in=user_ids):
        users[user.id] = user

    for message in messages:
        recipient_user_id = int(message['recipient_user_id'])

        try:
            recipient_user = users[recipient_user_id]
        except KeyError:
            logger.error(f'Tried to send email but user doesnt exist. Email: { dumps(message) }. '
                         f'User: { recipient_user_id }')
            continue

        try:
            subject = message['subject']
            text = message['message']
            email_message = message.get('email_message', text)

            if 'sender' in message:
                sender = message['sender']
                sender_user = User.objects.get(id=sender)
            else:
                sender = settings.EMAIL_SITE
                sender_user = recipient_user

            my_message = Message(subject=subject,
                                 body=mark_safe(text),
                                 sender=sender_user,
                                 recipient=recipient_user)

            message_list.append(my_message)

            http_message = {'html_message': email_message} if 'http' in email_message else {}

            send_mail(
                subject=subject,
                message=email_message,
                from_email=sender,
                recipient_list=[recipient_user.email],
                fail_silently=False,
                **http_message
            )
        except KeyError:
            logger.error(f'Missing key. Email: { dumps(message) }. '
                         f'User: { recipient_user_id }')

    if len(message_list) > 0:
        Message.objects.bulk_create(message_list)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants