from datetime import datetime from celery import shared_task from django.core.mail import send_mail from notification.models import Subscriber from news import models from django.template.loader import render_to_string, get_template from django.conf import settings from smtplib import SMTPException from django.core.validators import EMPTY_VALUES from main.models import SiteSettings @shared_task def send_email_with_news(news_ids): subscribers = Subscriber.objects.filter(state=Subscriber.USABLE) sent_news = models.News.objects.filter(id__in=news_ids) htmly = get_template(settings.NEWS_EMAIL_TEMPLATE) year = datetime.now().year socials = list(SiteSettings.objects.with_country()) socials = dict(zip(map(lambda s: s.country.code, socials), socials)) for s in subscribers: socials_for_subscriber = socials.get(s.country_code) try: for n in sent_news: context = {"title": n.title.get(s.locale), "subtitle": n.subtitle.get(s.locale), "description": n.description.get(s.locale), "code": s.update_code, "image_url": n.image_url if n.image_url not in EMPTY_VALUES else None, "domain_uri": settings.DOMAIN_URI, "slug": n.slug, "country_code": s.country_code, "twitter_page_url": socials_for_subscriber.twitter_page_url if socials_for_subscriber else '#', "instagram_page_url": socials_for_subscriber.instagram_page_url if socials_for_subscriber else '#', "facebook_page_url": socials_for_subscriber.facebook_page_url if socials_for_subscriber else '#', "send_to": s.send_to, "year": year} send_mail("G&M News", render_to_string(settings.NEWS_EMAIL_TEMPLATE, context), settings.EMAIL_HOST_USER, [s.send_to], fail_silently=False, html_message=htmly.render(context)) except SMTPException: continue