61 lines
2.5 KiB
Python
61 lines
2.5 KiB
Python
from datetime import datetime
|
|
from smtplib import SMTPException
|
|
|
|
from celery import shared_task
|
|
from django.conf import settings
|
|
from django.core.mail import send_mail
|
|
from django.core.validators import EMPTY_VALUES
|
|
from django.template.loader import get_template, render_to_string
|
|
|
|
from main.models import SiteSettings
|
|
from news import models
|
|
from notification.models import Subscribe
|
|
|
|
|
|
@shared_task
|
|
def send_email_with_news(news_ids):
|
|
subscribes = Subscribe.objects.all() \
|
|
.prefetch_related('subscriber') \
|
|
.prefetch_related('subscription_type')
|
|
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().select_related('country'))
|
|
socials = dict(zip(map(lambda social: social.country.code, socials), socials))
|
|
|
|
for subscribe in subscribes.filter(unsubscribe_date=None):
|
|
country = subscribe.subscription_type.country
|
|
|
|
if country is None:
|
|
continue
|
|
|
|
socials_for_subscriber = socials.get(country.code)
|
|
subscriber = subscribe.subscriber
|
|
|
|
try:
|
|
for new in sent_news:
|
|
context = {
|
|
"title": new.title.get(subscriber.locale),
|
|
"subtitle": new.subtitle.get(subscriber.locale),
|
|
"description": new.description.get(subscriber.locale),
|
|
"code": subscriber.update_code,
|
|
"image_url": new.image_url if new.image_url not in EMPTY_VALUES else None,
|
|
"domain_uri": settings.DOMAIN_URI,
|
|
"slug": new.slug,
|
|
"country_code": subscriber.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": subscriber.send_to,
|
|
"year": year
|
|
}
|
|
send_mail(
|
|
"G&M News", render_to_string(settings.NEWS_EMAIL_TEMPLATE, context),
|
|
settings.EMAIL_HOST_USER, [subscriber.send_to], fail_silently=False,
|
|
html_message=htmly.render(context)
|
|
)
|
|
except SMTPException:
|
|
continue
|