def send_now(users, label, extra_context=None, on_site=True, preference=None): """ Creates a new notice. This is intended to be how other apps create new notices. notification.send(user, 'friends_invite_sent', { 'spam': 'eggs', 'foo': 'bar', ) You can pass in on_site=False to prevent the notice emitted from being displayed on the site. """ if extra_context is None: extra_context = {} notice_type = NoticeType.objects.get(label=label) current_site = Site.objects.get_current() notices_url = u"http://%s%s" % ( unicode(current_site), reverse("notification_notices"), ) current_language = get_language() formats = ( 'short.txt', 'full.txt', 'notice.html', 'full.html', ) # TODO make formats configurable for user in users: if preference: if user.get_profile().get_preference(preference) == "off": continue recipients = [] # get user language for user from language store defined in # NOTIFICATION_LANGUAGE_MODULE setting try: language = get_notification_language(user) except LanguageStoreNotAvailable: language = None if language is not None: # activate the user's language activate(language) # update context with user specific translations context = Context({ "user": user, "notice": ugettext(notice_type.display), "notices_url": notices_url, "current_site": current_site, }) context.update(extra_context) # get prerendered format messages messages = get_formatted_messages(formats, label, context) # Strip newlines from subject subject = ''.join( render_to_string('notification/email_subject.txt', { 'message': messages['short.txt'], }, context).splitlines()) body_html = render_to_string('notification/email_body.html', { 'message': messages['full.txt'], }, context) body_txt = render_to_string('notification/email_body.txt', { 'message': messages['full.txt'], }, context) notice = Notice.objects.create(user=user, message=body_html, notice_type=notice_type, on_site=on_site) if should_send(user, notice_type, "1") and user.email: # Email recipients.append(user.email) # send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, recipients) # tutaj wysylany jest mail!!! msg = EmailMultiAlternatives(subject, body_txt, settings.DEFAULT_FROM_EMAIL, [ user.email, ]) msg.attach_alternative(body_html, "text/html") msg.send(fail_silently=True) # reset environment to original language activate(current_language)
def email(subject, template_name, context, recipients, preheader=None, bcc=None, reply_to=None, send=True): from django.conf import settings if not (subject and template_name and context and recipients): raise NameError() if not isinstance(recipients, list): raise TypeError("recipients must be a list") # bcc is set to False by default. # make sure bcc is in a list form when sent over if bcc not in [False, None] and not isinstance(bcc, list): raise TypeError("recipients must be a list") context['subject'] = subject context['current_year'] = timezone.now().year context['company_name'] = settings.SITE_NAME context['site_url'] = settings.SITE_URL if preheader: context['preheader'] = preheader html_content = render_to_string('{}.html'.format(template_name), context) text_content = render_to_string('{}.txt'.format(template_name), context) msg = EmailMultiAlternatives(subject=subject, body=text_content, from_email=u'CoderDojoChi<{}>'.format( settings.DEFAULT_FROM_EMAIL), to=recipients) if reply_to: msg.reply_to = reply_to msg.inline_css = True msg.attach_alternative(html_content, "text/html") if send: try: msg.send() except Exception as e: response = msg.mandrill_response[0] logger.error(u'{}'.format(response)) reject_reasons = [ 'hard-bounce', 'soft-bounce', 'spam', 'unsub', 'custom', ] if (response['status'] == u'rejected' and response['reject_reason'] in reject_reasons): logger.error('user: {}, {}'.format(response['email'], timezone.now())) from coderdojochi.models import CDCUser user = CDCUser.objects.get(email=response['email']) user.is_active = False user.admin_notes = u'User \'{}\' when checked on {}'.format( response['reject_reason'], timezone.now()) user.save() else: raise e return msg
def run(self): msg = EmailMultiAlternatives(self.subject, self.body, self.from_email, self.recipient_list) if self.html: msg.attach_alternative(self.html, "text/html") msg.send(self.fail_silently)
def send_contact_mail(subject, message, from_email): msg = EmailMultiAlternatives(subject, message, from_email, [config('ADMIN_EMAIL')]) msg.attach_alternative(message, "text/plain")
html_email_body = f""" <p>Hi there from the <a href="https://saveourfaves.org/">SaveOurFaves.org</a> team! We’re a volunteer website trying to support Bay Area businesses during the COVID-19 crisis. The following people told us via our site that they want to buy gift cards from {place_name}:</p> <p> {html_emails_to_notify_about}</p> <p>We encourage you to email them a link where they can buy gift cards online. If you don’t have an online gift card service yet, one that we like is <a href="http://www.giftfly.com/">Gift Fly</a>, since they don’t charge too much and they will deposit funds directly to your bank account. Otherwise you can ask customers to call you so you can do it over the phone.</p> <p>We’d also like to post your gift card link on SaveOurFaves.org so more people can buy from you. <a href="https://saveourfaves.org/addplace">Share your link with us here</a>.</p> <p>Thank you, and sending you the best during this crazy time.</p> <p>Cheers,<br/> The SaveOurFaves team</p> """ if not really_send: print("Would have sent to %s: %s" % (to_address, place_name)) continue message = EmailMultiAlternatives( subject=f"Buying a gift card to support {place_name}", body=plain_email_body, from_email="SavingChinatown Team <*****@*****.**>", to=[to_address], bcc=['*****@*****.**'], connection=connection, ) message.attach_alternative(html_email_body, 'text/html') message.send() print("Sent email to", place_name, to_address) EmailSubscription.objects.filter(pk__in=sub_pks).update(processed=True)
def send_email(league, template, to_email, context={}): context['league'] = league context['url_domain'] = settings.URL_DOMAIN if league.email_from_name: from_email = "{} <{}>".format(league.email_from_name, league.email_from_address) else: from_email = league.email_from_address # the to_name field isn't working so hot right now for some mysterious reason. #if to_user: # #to = "{} <{}>".format(to_user, to_user.email) # to = "{}".format(to_user.email) #elif to_email and to_name: # to = "{} <{}>".format(to_name, to_email) if to_email: to = "{}".format(to_email) else: raise ValueError( "No user or email address passed, unable to send email.") # maybe these would be useful at some point? #context['from_email'] = from_email #context['to_email'] = name, etc? # Get header HTML #if league.email_header: # context['header_html'] = league.email_header #else: context['header_html'] = render_to_string('email/header_default.html', context) # Get footer HTML #if league.email_footer: # context['footer_html'] = league.email_footer #else: context['footer_html'] = render_to_string('email/footer_default.html', context) subject = render_to_string('email/{}.subject'.format(template), context) message_html = render_to_string('email/{}.html'.format(template), context) try: message_txt = render_to_string('email/{}.txt'.format(template), context) except TemplateDoesNotExist: # By default we'll use BeautifulSoup for generating the text version # This kinda sucks, but otherwise we'll be creating raw text versions # of all the emails. Nobody really needs those anyway.... oh well. from bs4 import BeautifulSoup message_txt = BeautifulSoup(message_html, "html.parser").get_text("\n", strip=True) cc = None if league.email_cc_address: cc = [ league.email_cc_address, ] msg = EmailMultiAlternatives( subject=subject, body=message_txt, from_email=from_email, to=[ to_email, ], reply_to=[ from_email, ], cc=cc, ) msg.attach_alternative(message_html, "text/html") msg.send(fail_silently=False)
def volunteerForUser(request, slot_id, user_id): thisUser = User.objects.get(id=user_id) # next = request.GET.get('next') slot = Slot.objects.get(id=slot_id) group = slot.get_group() if group.get_is_organzer(request.user): user_slot = User_Slot.objects.filter(parentSlot=slot, volunteer__isnull=True).first() slots_filled_by_this_user = User_Slot.objects.filter( parentSlot=slot, volunteer=thisUser).first() # This stops people from signing up twice # if slots_filled_by_this_user is not None: # alert = Alert(user=thisUser, text="Already volunteered", color=Alert.getRed()) # alert.saveIP(request) # return redirect('/volunteer/slot/' + str(slot_id)) if user_slot is None: addUserSlot(request, slot_id) user_slot = User_Slot.objects.filter( parentSlot=slot, volunteer__isnull=True).first() user_slot.volunteer = thisUser user_slot.accepted = "No" user_slot.save() name = slot.title feed_entry = Feed_Entry(group=group, user=thisUser, datetime=get_dt(), description="Accept volunteer for " + name, url="/volunteer/slot/" + str(slot.id), private=slot.private) feed_entry.save() alert = Alert(user=thisUser, text="Volunteered for " + slot.title, color=Alert.getGreen()) alert.saveIP(request) current_site = get_current_site(request) # Sends the user an email based on the email template and the info passed in here message = render_to_string( 'emails/volentold.html', { 'user': thisUser, 'domain': current_site.domain, 'slot': slot, 'group': group, }) mail_subject = 'You have been added to a slot' to_email = thisUser.email email = EmailMultiAlternatives(mail_subject, message, to=[to_email]) email.content_subtype = 'html' email.mixed_subtype = 'related' fp = open('static/img/logos.ico/ms-icon-70x70.png', 'rb') logo = MIMEImage(fp.read()) logo.add_header('Content-ID', '<logo>') email.attach(logo) email.send() return redirect('/volunteer/slot/' + str(slot.id))
def confirm(request): subs = [['Login', 'cadastramento de usuário'], ['OK', 'tudo certo!'], ['ERRO', 'ha algo de arrado']] erro = None url = "https://fsfwefdefeeddfcef.herokuapp.com/register" if request.method == "POST": #pegou o email do user email = request.POST.get('email') senha = request.POST.get('senha') if email != None and senha == None: data = {'email': email} try: tk = requests.post(url=url, data=data) except: erro = 'problemas de conexão ao servidor, recarregue a pagina e tente novamente' return render( request, 'index.html', dict(view='login.html', title=title, subtitle=subs[0], mode="1", email=email, erro=erro)) turl = siteurl + "confirm?" + tk.text htmlEmail = """<h3>Termine seu cadastro na NinosApp </h3> <p>Para terminar seu cadrastro, <a href="{turl}">click aqui</a><p><br/> <p><font color="#f00">obs: </font> você tem apenas 10 minutos para realizar seu cadastro, caso nao seja confirmado, acesse {url} e faça esta etapa novamente </p><br/> <small>Esta é uma menssagem enviada altomaticamente. Por favor não responsa.</small>""".format( url=siteurl, turl=turl) sub = "termine seu cadastro na NinosApp" text_content = '' f = '*****@*****.**' try: msg = EmailMultiAlternatives(sub, text_content, f, [email]) msg.attach_alternative(htmlEmail, 'text/html') msg.send() except: erro = 'email invalido!' return render( request, 'index.html', dict(view='login.html', title=title, subtitle=subs[0], mode="1", erro=erro)) return render( request, 'index.html', dict(view='next.html', title=title, subtitle=subs[1], form={"token": tk.text})) else: return redirect('home') elif request.method == "GET": token = request.GET.get('t') if token == None: return render( request, 'index.html', dict(title=title, view='error.html', e=0, erro='ERRO 404')) else: try: url = "https://fsfwefdefeeddfcef.herokuapp.com/register" tk = requests.post(url=url) except: return render( request, 'index.html', dict(title=title, view='error.html', subtitle=subs[2], e=1, erro='codigo de confirmação inválido')) else: return redirect('home')
def receive_sms(request): # TODO - secure this callback sender = request.POST.get('From') message = request.POST.get('Body') STOP_LIST = ['STOP', 'STOPALL', 'UNSUBSCRIBE', 'CANCEL', 'END', 'QUIT'] command = message.strip(string.punctuation + string.whitespace).upper() opt_out = command in STOP_LIST if opt_out: application_mobile_opt_out(sender) return http.HttpResponse(status=200) START_LIST = ['START', 'YES', 'UNSTOP'] opt_in = command in START_LIST if opt_in: application_mobile_opt_out_revert(sender) return http.HttpResponse(status=200) to = [] bcc = None subject = 'New SMS reply from {0}'.format(sender) context = { 'message': message, 'sender': sender, } # Only forward message to facilitator if there is a meeting in the future-ish today = datetime.datetime.now().date() yesterday = today - datetime.timedelta(days=1) meetings = Meeting.objects.active().filter(meeting_date__gte=yesterday) signups = Application.objects.active().filter( Q(mobile=sender) & Q(mobile_opt_out_at__isnull=True) & Q(study_group__in=meetings.values('study_group'))) # TODO handle user signed up to 2 learning circles if signups.count() == 1: signup = signups.first() context['signup'] = signup # TODO i18n subject = 'New SMS reply from {0} <{1}>'.format(signup.name, sender) to += [signup.study_group.facilitator.email] next_meeting = signups.first().study_group.next_meeting() # TODO - replace this check with a check to see if the meeting reminder has been sent if next_meeting and next_meeting.meeting_datetime() - timezone.now( ) < datetime.timedelta(days=2): context['next_meeting'] = next_meeting context['rsvp_yes'] = next_meeting.rsvp_yes_link(sender) context['rsvp_no'] = next_meeting.rsvp_no_link(sender) text_body = render_to_string_ctx('studygroups/email/incoming_sms.txt', context) html_body = render_to_string_ctx('studygroups/email/incoming_sms.html', context) if len(to) == 0: to = [a[1] for a in settings.ADMINS] else: bcc = [a[1] for a in settings.ADMINS] notification = EmailMultiAlternatives(subject, text_body, settings.DEFAULT_FROM_EMAIL, to, bcc) notification.attach_alternative(html_body, 'text/html') notification.send() return http.HttpResponse(status=200)
def test_send_messages(self, queue): message = EmailMultiAlternatives() backends.EmailBackend().send_messages([message]) queue.assert_called_with([message])
def test_send_messages2(self, send): with self.settings(EMAIL_QUEUE_EAGER=True): message = EmailMultiAlternatives(to=["*****@*****.**"]) backends.EmailBackend().send_messages([message]) self.assertTrue(send.called)
def test_no_recipients(self): email_message = EmailMultiAlternatives("foo", "bar", "*****@*****.**") email_message.attach_alternative("some", "text/json") generator = QueuedEmailMessage.queue([email_message]) self.assertRaises(AssertionError, list, generator)
def message(): return EmailMultiAlternatives(subject="subject", body="text_content", from_email="*****@*****.**", to=["*****@*****.**"])
def send_activation_email(self, site, request=None): """ Send an activation email to the user associated with this ``RegistrationProfile``. The activation email will make use of two templates: ``registration/activation_email_subject.txt`` This template will be used for the subject line of the email. Because it is used as the subject line of an email, this template's output **must** be only a single line of text; output longer than one line will be forcibly joined into only a single line. ``registration/activation_email.txt`` This template will be used for the text body of the email. ``registration/activation_email.html`` This template will be used for the html body of the email. These templates will each receive the following context variables: ``user`` The new user account ``activation_key`` The activation key for the new account. ``expiration_days`` The number of days remaining during which the account may be activated. ``site`` An object representing the site on which the user registered; depending on whether ``django.contrib.sites`` is installed, this may be an instance of either ``django.contrib.sites.models.Site`` (if the sites application is installed) or ``django.contrib.sites.models.RequestSite`` (if not). Consult the documentation for the Django sites framework for details regarding these objects' interfaces. ``request`` Optional Django's ``HttpRequest`` object from view. If supplied will be passed to the template for better flexibility via ``RequestContext``. """ ctx_dict = {} if request is not None: ctx_dict = RequestContext(request, ctx_dict) # update ctx_dict after RequestContext is created # because template context processors # can overwrite some of the values like user # if django.contrib.auth.context_processors.auth is used ctx_dict.update({ 'user': self.user, 'activation_key': self.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': site, }) subject = getattr(settings, 'REGISTRATION_EMAIL_SUBJECT_PREFIX', '') + \ render_to_string('registration/activation_email_subject.txt', ctx_dict) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) message_txt = render_to_string('registration/activation_email.txt', ctx_dict) email_message = EmailMultiAlternatives(subject, message_txt, settings.DEFAULT_FROM_EMAIL, [self.user.email]) try: message_html = render_to_string( 'registration/activation_email.html', ctx_dict) except TemplateDoesNotExist: message_html = None if message_html: email_message.attach_alternative(message_html, 'text/html') email_message.send()
def send_message_mp(author, n_topic, text, send_by_mail=True, direct=False, hat=None, no_notification_for=None): """ Send a post in an MP. :param author: sender of the private message :param n_topic: topic in which it will be sent :param text: content of the message :param send_by_mail: if True, also notify by email :param direct: send a mail directly without private message (ex : banned members who won't connect again) :param hat: hat attached to the message :param no_notification_for: list of participants who won't be notified of the message """ # Getting the position of the post if n_topic.last_message is None: pos = 1 else: pos = n_topic.last_message.position_in_topic + 1 # Add the first message post = PrivatePost() post.privatetopic = n_topic post.author = author post.text = text post.text_html = emarkdown(text) post.pubdate = datetime.now() post.position_in_topic = pos post.hat = hat post.save() n_topic.last_message = post n_topic.save() if not direct: signals.message_added.send(sender=post.__class__, post=post, by_email=send_by_mail, no_notification_for=no_notification_for) if send_by_mail and direct: subject = "{} : {}".format(settings.ZDS_APP["site"]["literal_name"], n_topic.title) from_email = "{} <{}>".format( settings.ZDS_APP["site"]["literal_name"], settings.ZDS_APP["site"]["email_noreply"]) for recipient in n_topic.participants.values_list("email", flat=True): message_html = render_to_string("email/direct.html", {"msg": emarkdown(text)}) message_txt = render_to_string("email/direct.txt", {"msg": text}) msg = EmailMultiAlternatives(subject, message_txt, from_email, [recipient]) msg.attach_alternative(message_html, "text/html") try: msg.send() except Exception as e: logger.exception("Message was not sent to %s due to %s", recipient, e) if no_notification_for: if not isinstance(no_notification_for, list): no_notification_for = [no_notification_for] for not_notified_user in no_notification_for: mark_read(n_topic, not_notified_user) # There's no need to inform of the new participant # because participants are already notified through the `message_added` signal. # If we tried to add the bot, that's fine (a better solution would be welcome though) with suppress(NotReachableError): n_topic.add_participant(author, silent=True) n_topic.save() return n_topic
def send_user_token_email( user=None, request=None, subject_template_name=None, from_email=None, # settings.EMAIL_HOST_USER, email_template_name=None, html_email_template_name=None, token_generator=default_token_generator, site_name=None, site_url=None, extra_email_context=None): '''Sends an email to a user with a uid/token link to reset password. user - existing user in db request - request from view where function is called subject_template_name - text file containing the email subject from_email - email address of sender email_template_name - template containing email body html_email_template - html-formatted template to display email_template token_generator - generate token based on user site name - name of project site_url - main project url extra_email_context - dict containing extra email context variables ''' if not user or not request or not subject_template_name or not email_template_name: pass uid = urlsafe_base64_encode(force_bytes(user.pk)) token = token_generator.make_token(user) token_url = request.build_absolute_uri( reverse('users:user_forgot_password_reset', kwargs={ 'uidb64': uid, 'token': token })) if site_name is None: if hasattr(settings, 'PROJECT_NAME'): site_name = settings.PROJECT_NAME if site_url is None: if hasattr(settings, 'PROJECT_HOME_URL'): site_url = request.build_absolute_uri( reverse(settings.PROJECT_HOME_URL)) else: site_url = request.build_absolute_uri('/') else: site_url = request.build_absolute_uri(reverse(site_url)) context = { 'request': request, 'username': user, 'site_url': site_url, 'site_name': site_name, 'token_url': token_url } if extra_email_context is not None: context.update(extra_email_context) ''' Sends a django.core.mail.EmailMultiAlternatives to `to_email`. ''' subject = loader.render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [user.email]) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, 'text/html') email_message.send()
import os from django.core.mail import EmailMultiAlternatives os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DangDang.settings") if __name__ == '__main__': # 1. 发给谁 2. 从哪儿发 3. 发点啥 to = ['*****@*****.**'] from_email = '*****@*****.**' subject = 'test' comment = 'test1' html_content = '<a href="http://www.baidu.com">test</a>' msg = EmailMultiAlternatives(html_content, from_email=from_email, body=comment, to=to) msg.send()
import os from django.core.mail import send_mail from django.core.mail import EmailMultiAlternatives os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' if __name__ == '__main__': subject, from_email, to = '来自www.liujiangblog.com的测试邮件', '*****@*****.**', '*****@*****.**' text_content = '欢迎访问www.liujiangblog.com,这里是刘江的博客和教程站点,专注于Python和Django技术的分享!' html_content = '<p>欢迎访问<a href="http://www.liujiangblog.com" target=blank>www.liujiangblog.com</a>,这里是刘江的博客和教程站点,本站专注于Python、Django和机器学习技术的分享!</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send()
def send_resume_reminders(request): # Send e-mails successful = 0 failed = 0 if request.method == "POST": # Get threshold date months = int(request.POST["reminder_duration"]) threshold_date = datetime.now() - timedelta(days=30 * months) # Get people to send e-mails to people = ResumePerson.objects.filter( resume_reminded_at__lt=threshold_date, resume_reminder_subscribed__exact=True) # Send e-mails current_site = request.META['HTTP_HOST'] for person in people: email_url = ("http://" + current_site + "/corporate/resume/student/referred" "?resume_uuid=" + person.resume_uuid) unsubscribe_url = ("http://" + current_site + "/corporate/resume/student/unsubscribe" + "?resume_uuid=" + person.resume_uuid) email_text = get_template( 'intranet/resume_manager/emails/resume_reminder.txt') email_html = get_template( 'intranet/resume_manager/emails/resume_reminder.html') email_context = Context({ "person": person, "email_url": email_url, "unsubscribe_url": unsubscribe_url }) email_text = email_text.render(email_context) email_html = email_html.render(email_context) try: msg = EmailMultiAlternatives("ACM@UIUC Resume Book", email_text, "*****@*****.**", [person.netid + "@illinois.edu"]) msg.attach_alternative(email_html, "text/html") msg.send() successful += 1 # Update sent date person.resume_reminded_at = datetime.now() person.save() except: failed += 1 pass messages.add_message( request, messages.INFO, str(successful + failed) + ' e-mail sends were attempted.') if successful != 0: messages.add_message( request, messages.SUCCESS, str(successful) + ' e-mail(s) were successfully sent!') if failed != 0: messages.add_message(request, messages.ERROR, str(failed) + ' e-mail(s) failed to send.') # Get sizes of e-mail groups threshold_date_0 = datetime.now() threshold_date_1 = datetime.now() - timedelta(days=30) threshold_date_3 = datetime.now() - timedelta(days=90) threshold_date_6 = datetime.now() - timedelta(days=180) threshold_date_12 = datetime.now() - timedelta(days=360) people_all = ResumePerson.objects.filter(resume_reminder_subscribed=True) people_count_0 = people_all.filter( resume_reminded_at__lt=threshold_date_0).count() people_count_1 = people_all.filter( resume_reminded_at__lt=threshold_date_1).count() people_count_3 = people_all.filter( resume_reminded_at__lt=threshold_date_3).count() people_count_6 = people_all.filter( resume_reminded_at__lt=threshold_date_6).count() people_count_12 = people_all.filter( resume_reminded_at__lt=threshold_date_12).count() people_array = ["nobody", " person", " people"] return render_to_response('intranet/resume_manager/resume_reminder.html', { "section": "intranet", "page": "resume", "sub_page": "send_reminders", "people_0": (str(people_count_0) if people_count_0 != 0 else "") + people_array[min(people_count_0, 2)], "people_1": (str(people_count_1) if people_count_1 != 0 else "") + people_array[min(people_count_1, 2)], "people_3": (str(people_count_3) if people_count_3 != 0 else "") + people_array[min(people_count_3, 2)], "people_6": (str(people_count_6) if people_count_6 != 0 else "") + people_array[min(people_count_6, 2)], "people_12": (str(people_count_12) if people_count_12 != 0 else "") + people_array[min(people_count_12, 2)] }, context_instance=RequestContext(request))
def submit(self): subscriptions = self.subscriptions.filter(subscribed=True) logger.info(ugettext(u"Submitting %(submission)s to %(count)d people"), { 'submission': self, 'count': subscriptions.count() }) assert self.publish_date < now(), \ 'Something smells fishy; submission time in future.' self.sending = True self.save() try: (subject_template, text_template, html_template) = \ self.message.newsletter.get_templates('message') for subscription in subscriptions: variable_dict = { 'subscription': subscription, 'site': Site.objects.get_current(), 'submission': self, 'message': self.message, 'newsletter': self.newsletter, 'date': self.publish_date, 'STATIC_URL': settings.STATIC_URL, 'MEDIA_URL': settings.MEDIA_URL } unescaped_context = Context(variable_dict, autoescape=False) message = EmailMultiAlternatives( subject_template.render(unescaped_context), text_template.render(unescaped_context), from_email=self.newsletter.get_sender(), to=[subscription.get_recipient()]) if html_template: escaped_context = Context(variable_dict) message.attach_alternative( html_template.render(escaped_context), "text/html") try: logger.debug(ugettext(u'Submitting message to: %s.'), subscription) message.send() except Exception, e: # TODO: Test coverage for this branch. logger.error( ugettext(u'Message %(subscription)s failed ' u'with error: %(error)s'), { 'subscription': subscription, 'error': e }) self.sent = True
def badminton_time_details(request, date, time): if request.user.is_authenticated: upcoming_game = Registered_Players.objects.filter(user=request.user) else: upcoming_game = str(0) obj = Registered_Players.objects.filter(game="Badminton", date=date, time=time).count() # print(obj) if obj == 2: messages.success( request, 'Slot is filled for selected date ' + date + ' and time ' + time + ' . Try another Slot.') all_details = { 'selected_date': date, 'selected_time': time, 'upcoming_game': upcoming_game, 'friend_chat': Friends.objects.filter( Q(friend_1__icontains=request.user) | Q(friend_2__icontains=request.user)).distinct() } return render(request, 'index/badminton_time_details.html', context=all_details) if request.method == 'POST': user = request.user full_name = request.POST.get('full_name') registration = request.POST.get('registration') email = request.POST.get('email') game = request.POST.get('game') status = request.POST.get('status') date = request.POST.get('date') time = request.POST.get('time') Registered_Players.objects.create(user=user, full_name=full_name, registration_no=registration, email=email, game=game, date=date, time=time) subject, from_email, to = 'Registered for Game', '*****@*****.**', email html_content = render_to_string( "mail_template/game_registered.html", { 'name': request.POST.get('full_name').capitalize(), 'game': game, 'date': date, 'time': time, }) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return redirect('/') all_details = { 'selected_date': date, 'selected_time': time, 'upcoming_game': upcoming_game, 'friend_chat': Friends.objects.filter( Q(friend_1__icontains=request.user) | Q(friend_2__icontains=request.user)).distinct() } return render(request, 'index/badminton_time_details.html', context=all_details)
def payment_form_view(request): record = get_record(request) if not record.offer_agreement: # Redirect to offer-agreement if user haven't agreed return redirect("purchase:offer-agreement") elif not record.is_ready(): # Redirect to form if it is not valid return redirect("purchase:entity-form" ) if record.get_entity_payer_or_none() else redirect( "purchase:individual-form") elif not record.is_confirmed(): return redirect("purchase:confirmation-form") elif record.finished: return redirect("purchase:finished") if request.method == "POST": form = PaymentForm(request.POST) if form.is_valid(): # Finish purchase payment_type = form.cleaned_data.get("payment_type") record.payment_type = payment_type record.date_finished = timezone.now() record.save() # Send mail with full information to workers and payer if payment_type == "payme": payment_link = get_payment_link( record.id, record.get_9_digit_phone(), record.get_amount() * 100, request.LANGUAGE_CODE, request.build_absolute_uri(reverse("purchase:finished"))) else: payment_link = None build_invoice(record, request) html_context = { "payer": record.payer, "students_list": get_students_list(record), "mail": True, "payment_link": payment_link } plain_context = { "payer": record.payer, "students_list": record.students.all(), "mail": True } html_content = render_to_string("purchase/mail/html_mail.html", html_context, request=request) text_content = strip_tags( render_to_string("purchase/mail/text_mail.html", plain_context)) mail = EmailMultiAlternatives( subject="Новая покупка", body=text_content, from_email=EMAIL_PAYMENT_NOTIFICATION_USER, to=STAFF_MAILS + [record.payer.email()]) with open(BASE_DIR / "static" / "css" / "mail.css", 'r') as css: css = css.read().replace('\n', '') mail.attach_alternative(transform(html_content, css_text=css), 'text/html') # Attach html version # Attach files for student in record.students.all(): archive_name = student.folder_path / f"{student.name}.zip" with ZipFile(archive_name, "w") as archive: archive.write( student.passport_path, STUDENT_PASSPORT + student.passport_path.suffix) archive.write( student.study_document_path, STUDY_DOCUMENT + student.study_document_path.suffix) with open(archive_name, "rb") as archive: mail.attach(archive_name.name, archive.read()) archive_name.unlink() mail.attach(INVOICE + record.invoice_path.suffix, record.invoice_path.read_bytes()) if record.get_individual_payer_or_none() is not None: mail.attach(PAYER_PASSPORT + record.payer.passport_path.suffix, record.payer.passport_path.read_bytes()) result = mail.send() request.session["allow_media"] = record.id delete_session_purchase_record(request) if not record.finished: record.finish() if result: if payment_type == "payme": return redirect("purchase:payme-payment") else: return redirect("purchase:finished") else: return HttpResponseServerError( _("Что-то пошло не так при оформлении заказа. Разработчик был уведомлён об ошибке. Приносим свои извинения" )) form = PaymentForm(instance=record) context = { "record": record, "form": form, } return render(request, "purchase/payment-form.html", context)
def send_activation_email(self, site, request=None): """ Send an activation email to the user associated with this ``RegistrationProfile``. The activation email will use the following templates, which can be overridden by setting ACTIVATION_EMAIL_SUBJECT, ACTIVATION_EMAIL_BODY, and ACTIVATION_EMAIL_HTML appropriately: ``registration/activation_email_subject.txt`` This template will be used for the subject line of the email. Because it is used as the subject line of an email, this template's output **must** be only a single line of text; output longer than one line will be forcibly joined into only a single line. ``registration/activation_email.txt`` This template will be used for the text body of the email. ``registration/activation_email.html`` This template will be used for the html body of the email. These templates will each receive the following context variables: ``user`` The new user account ``activation_key`` The activation key for the new account. ``expiration_days`` The number of days remaining during which the account may be activated. ``site`` An object representing the site on which the user registered; depending on whether ``django.contrib.sites`` is installed, this may be an instance of either ``django.contrib.sites.models.Site`` (if the sites application is installed) or ``django.contrib.sites.requests.RequestSite`` (if not). Consult the documentation for the Django sites framework for details regarding these objects' interfaces. ``request`` Optional Django's ``HttpRequest`` object from view. If supplied will be passed to the template for better flexibility via ``RequestContext``. """ activation_email_subject = getattr( settings, 'ACTIVATION_EMAIL_SUBJECT', 'registration/activation_email_subject.txt') activation_email_body = getattr(settings, 'ACTIVATION_EMAIL_BODY', 'registration/activation_email.txt') activation_email_html = getattr(settings, 'ACTIVATION_EMAIL_HTML', 'registration/activation_email.html') ctx_dict = { 'user': self.user, 'activation_key': self.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': site, } prefix = getattr(settings, 'REGISTRATION_EMAIL_SUBJECT_PREFIX', '') subject = prefix + render_to_string( activation_email_subject, ctx_dict, request=request) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) from_email = get_from_email(site) message_txt = render_to_string(activation_email_body, ctx_dict, request=request) email_message = EmailMultiAlternatives(subject, message_txt, from_email, [self.user.email]) if getattr(settings, 'REGISTRATION_EMAIL_HTML', True): try: message_html = render_to_string(activation_email_html, ctx_dict, request=request) except TemplateDoesNotExist: pass else: email_message.attach_alternative(message_html, 'text/html') email_message.send()
def newsletter_signup(request): NewsletterUser2 = NewsletterUser.objects.all() count_users = NewsletterUser.objects.all().count() form = NewsletterUserSignUpForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if NewsletterUser.objects.filter(email=instance.email).exists(): messages.warning(request, 'Your Email already exists in our database', "alert alert-warning alert-dismissable") else: instance.save() messages.success( request, 'Your Email submitted to our database succesfully ', "alert alert-success alert-dismissable") subject = "Thank you for subscribing our newsletter" from_email = settings.EMAIL_HOST_USER to_email = [instance.email] #rec_emails =NewsletterUser.objects.all() # print(rec_emails) # print(len(rec_emails)) # query_list = [] #signup_message = """Welcome to visit+ newsletter.To UnSubscribe,Go To http://127.0.0.1:8000/newsletter/unsubscribe/""" #send_mail(subject=subject,from_email=from_email,recipient_list=to_email,message=signup_message,fail_silently=False) """"for ob in rec_emails: email = str(ob.email) query_list.append(email) if len(rec_emails) >=3: with open(settings.BASE_DIR + "/newsletters/templates/newsletters/sign_up_email.txt") as f: signup_message = f.read() message = EmailMultiAlternatives(subject=subject,body=signup_message,from_email=from_email,to=query_list) html_template = get_template("newsletters/sign_up_email.html").render() message.attach_alternative(html_template,"text/html") message.send() """ with open(settings.BASE_DIR + "/newsletters/templates/newsletters/sign_up_email.txt" ) as f: signup_message = f.read() message = EmailMultiAlternatives(subject=subject, body=signup_message, from_email=from_email, to=to_email) html_template = get_template( "newsletters/sign_up_email.html").render() message.attach_alternative(html_template, "text/html") message.send() print("Thank u mail sent") if count_industries == 17: print( "count_industries == 17 ,so sending emails to everyone indiviually" ) subject_News = "New Industry added to the database" rec_emails = NewsletterUser.objects.all() print(rec_emails) print(len(rec_emails)) query_list = [] for ob in rec_emails: email = str(ob.email) query_list.append(email) with open( settings.BASE_DIR + "/newsletters/templates/newsletters/New_Industry_Added.txt" ) as f: signup_message = f.read() print("Newsletters Sending to", query_list) message = EmailMultiAlternatives(subject=subject_News, body=signup_message, from_email=from_email, to=query_list) html_template = get_template( "newsletters/New_Industry_Added.html").render() message.attach_alternative(html_template, "text/html") message.send() print("Newsletters Sent to", query_list) query_list.pop() print("Newsletters Sent to all!!") context = { 'form': form, 'NewsletterUser2': NewsletterUser2, 'count': count_users, } return render(request, 'newsletters/sign_up.html', context)
def email_unread_notifications(timeframe): """ Looks for all unread notifications and sends each user one email with a summary. Marks any sent notifications as "read". timeframe may be: * 'daily' - only send to users who have the daily email setting * 'weekly' - only send to users who have the weekly email setting * 'all' - send all notifications """ from sefaria.model.notification import NotificationSet detect_potential_spam_message_notifications() users = db.notifications.find({ "read": False, "is_global": False }).distinct("uid") for uid in users: profile = UserProfile(id=uid) if profile.settings[ "email_notifications"] != timeframe and timeframe != 'all': continue notifications = NotificationSet().unread_personal_for_user(uid) if len(notifications) == 0: continue try: user = User.objects.get(id=uid) except User.DoesNotExist: continue if "interface_language" in profile.settings: translation.activate(profile.settings["interface_language"][0:2]) message_html = render_to_string("email/notifications_email.html", { "notifications": notifications, "recipient": user.first_name }) actors_string = notifications.actors_string() # TODO Hebrew subjects if actors_string: verb = "have" if " and " in actors_string else "has" subject = "%s %s new activity on Sefaria" % (actors_string, verb) elif notifications.like_count() > 0: noun = "likes" if notifications.like_count() > 1 else "like" subject = "%d new %s on your Source Sheet" % ( notifications.like_count(), noun) from_email = "Sefaria Notifications <*****@*****.**>" to = user.email msg = EmailMultiAlternatives(subject, message_html, from_email, [to]) msg.content_subtype = "html" try: msg.send() notifications.mark_read(via="email") except AnymailRecipientsRefused: print('bad email address: {}'.format(to)) if "interface_language" in profile.settings: translation.deactivate()
def send_mail(recipients, template, subject): from_email = settings.SERVER_EMAIL msg = EmailMultiAlternatives(subject, template, from_email, recipients) msg.attach_alternative(template, "text/html") msg.send()
def newlogin(request, pk): clup = SportsClub.objects.get(pk=pk) # clüp club_form = ClubForm(instance=clup) communication_formclup = CommunicationForm(instance=clup.communication) # klüp üyesi user_form = UserForm() person_form = PersonForm() communication_form = CommunicationForm() sportClubUser_form = SportClubUserForm() if request.method == 'POST': user_form = UserForm(request.POST) person_form = PersonForm(request.POST, request.FILES) communication_form = CommunicationForm(request.POST, request.FILES) sportClubUser_form = SportClubUserForm(request.POST) club_form = ClubForm(request.POST, request.FILES) communication_formclup = CommunicationForm(request.POST, request.FILES) if club_form.is_valid() and user_form.is_valid( ) and person_form.is_valid() and communication_form.is_valid( ) and sportClubUser_form.is_valid(): clup.name = request.POST.get('name') clup.shortName = request.POST.get('shortName') clup.foundingDate = request.POST.get('foundingDate') clup.logo = request.POST.get('logo') clup.clubMail = request.POST.get('clubMail') clup.isFormal = request.POST.get('isFormal') communication = communication_formclup.save(commit=False) communication.save() clup.communication = communication clup.save() messages.success(request, 'Bilgileriniz Başarıyla Güncellenmiştir.') user = User() user.username = user_form.cleaned_data['email'] user.first_name = user_form.cleaned_data['first_name'] user.last_name = user_form.cleaned_data['last_name'] user.email = user_form.cleaned_data['email'] group = Group.objects.get(name='KulupUye') user.save() user.groups.add(group) user.save() person = person_form.save(commit=False) communication = communication_form.save(commit=False) person.save() communication.save() club_person = SportClubUser( user=user, person=person, communication=communication, role=sportClubUser_form.cleaned_data['role'], ) club_person.save() fdk = Forgot(user=user, status=False) fdk.save() html_content = '' html_content = '' subject, from_email, to = 'Bilgi Sistemi Kullanıcı Bilgileri', '*****@*****.**', mail html_content = '<h2>ADALET BAKANLIGI PROJE TAKİP SİSTEMİ</h2>' html_content = html_content + '<p><strong>Kullanıcı Adınız :' + str( fdk.user.username) + '</strong></p>' # html_content = html_content + '<p> <strong>Site adresi:</strong> <a href="http://127.0.0.1:8000/newpassword?query=' + str( # fdk.uuid) + '">http://127.0.0.1:8000/sbs/profil-guncelle/?query=' + str(fdk.uuid) + '</p></a>' html_content = html_content + '<p> <strong>Site adresi:</strong> <a href="http://kobiltek.com:81/etutproje/newpassword?query=' + str( fdk.uuid ) + '">http://kobiltek.com:81/etutproje/sbs/profil-guncelle/?query=' + str( fdk.uuid) + '</p></a>' msg = EmailMultiAlternatives(subject, '', from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() clup.clubUser.add(club_person) clup.dataAccessControl = True clup.save() messages.success( request, 'Mail adresinize gelen link ile sisteme giriş yapabilirsiniz.') return redirect("accounts:login") # try: # # # except: # messages.warning(request, 'Lütfen Yeniden Deneyiniz') # return redirect("accounts:login") return render( request, 'registration/newlogin.html', { 'user_form': user_form, 'person_form': person_form, 'communication_form': communication_form, 'sportClubUser_form': sportClubUser_form, 'club_form': club_form, 'communication_formclup': communication_formclup })
def contact_us(request): owner = User.objects.get(id=request.GET.get('owner')) if ( request.GET.get('owner') and User.objects.filter(id=request.GET.get('owner')).first()) else None video = Video.objects.get(id=request.GET.get('video')) if ( request.GET.get('video') and Video.objects.filter( id=request.GET.get('video')).first()) else None description = "%s: %s\n%s: %s%s\n\n" % ( _('Title'), video.title, _('Link'), 'https:' if request.is_secure() else 'http:', video.get_full_url(request)) if video else None send_subject = request.GET.get('subject') if ( request.GET.get('subject') and request.GET.get('subject') in [key for key, value in SUBJECT_CHOICES]) else None prefix = 'https://' if request.is_secure() else 'http://' home_page = ''.join([prefix, get_current_site(request).domain]) url_referrer = request.META["HTTP_REFERER"] if request.META.get( "HTTP_REFERER") else home_page form = ContactUsForm(request, initial={ 'url_referrer': url_referrer, 'subject': send_subject, 'description': description }) if request.method == "POST": form = ContactUsForm(request, request.POST) if form.is_valid(): name = form.cleaned_data['name'] form_subject = form.cleaned_data['subject'] if ( form.cleaned_data.get('subject')) else send_subject subject = "[ %s ] %s" % (TITLE_SITE, dict(SUBJECT_CHOICES)[form_subject]) email = form.cleaned_data['email'] message = form.cleaned_data['description'] text_content = loader.get_template('mail/mail.txt').render({ 'name': name, 'email': email, 'TITLE_SITE': TITLE_SITE, 'message': message, 'url_referrer': form.cleaned_data['url_referrer'] }) html_content = loader.get_template('mail/mail.html').render({ 'name': name, 'email': email, 'TITLE_SITE': TITLE_SITE, 'message': message.replace("\n", "<br/>"), 'url_referrer': form.cleaned_data['url_referrer'] }) dest_email = [] dest_email = get_dest_email(owner, video, form_subject, request) msg = EmailMultiAlternatives(subject, text_content, email, dest_email) msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=False) # EMAIL TO SENDER subject = "[ %s ] %s %s" % (TITLE_SITE, _('your message untitled'), dict(SUBJECT_CHOICES)[form_subject]) text_content = loader.get_template('mail/mail_sender.txt').render({ 'TITLE_SITE': TITLE_SITE, 'message': message }) html_content = loader.get_template('mail/mail_sender.html').render( { 'TITLE_SITE': TITLE_SITE, 'message': message.replace("\n", "<br/>") }) msg = EmailMultiAlternatives(subject, text_content, DEFAULT_FROM_EMAIL, [email]) msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=False) messages.add_message(request, messages.INFO, _('Your message have been sent.')) return redirect(form.cleaned_data['url_referrer']) else: messages.add_message( request, messages.ERROR, _(u'One or more errors have been found in the form.')) return render(request, 'contact_us.html', {'form': form, 'owner': owner})
def mail_send_task(self, *args, to: List[str], subject: str, body: str, html: str, sender: str, event: int=None, position: int=None, headers: dict=None, bcc: List[str]=None, invoices: List[int]=None, order: int=None, attach_tickets=False, user=None, attach_ical=False) -> bool: email = EmailMultiAlternatives(subject, body, sender, to=to, bcc=bcc, headers=headers) if html is not None: html_with_cid, cid_images = replace_images_with_cid_paths(html) email = attach_cid_images(email, cid_images, verify_ssl=True) email.attach_alternative(html_with_cid, "text/html") if user: user = User.objects.get(pk=user) if event: with scopes_disabled(): event = Event.objects.get(id=event) backend = event.get_mail_backend() cm = lambda: scope(organizer=event.organizer) # noqa else: backend = get_connection(fail_silently=False) cm = lambda: scopes_disabled() # noqa with cm(): if invoices: invoices = Invoice.objects.filter(pk__in=invoices) for inv in invoices: if inv.file: try: with language(inv.order.locale): email.attach( pgettext('invoice', 'Invoice {num}').format(num=inv.number).replace(' ', '_') + '.pdf', inv.file.file.read(), 'application/pdf' ) except: logger.exception('Could not attach invoice to email') pass if event: if order: try: order = event.orders.get(pk=order) except Order.DoesNotExist: order = None else: if position: try: position = order.positions.get(pk=position) except OrderPosition.DoesNotExist: attach_tickets = False if attach_tickets: args = [] attach_size = 0 for name, ct in get_tickets_for_order(order, base_position=position): content = ct.file.read() args.append((name, content, ct.type)) attach_size += len(content) if attach_size < 4 * 1024 * 1024: # Do not attach more than 4MB, it will bounce way to often. for a in args: try: email.attach(*a) except: pass else: order.log_action( 'pretix.event.order.email.attachments.skipped', data={ 'subject': 'Attachments skipped', 'message': 'Attachment have not been send because {} bytes are likely too large to arrive.'.format(attach_size), 'recipient': '', 'invoices': [], } ) if attach_ical: ical_events = set() if event.has_subevents: if position: ical_events.add(position.subevent) else: for p in order.positions.all(): ical_events.add(p.subevent) else: ical_events.add(order.event) for i, e in enumerate(ical_events): cal = get_ical([e]) email.attach('event-{}.ics'.format(i), cal.serialize(), 'text/calendar') email = email_filter.send_chained(event, 'message', message=email, order=order, user=user) email = global_email_filter.send_chained(event, 'message', message=email, user=user, order=order) try: backend.send_messages([email]) except smtplib.SMTPResponseException as e: if e.smtp_code in (101, 111, 421, 422, 431, 442, 447, 452): self.retry(max_retries=5, countdown=2 ** (self.request.retries * 2)) logger.exception('Error sending email') if order: order.log_action( 'pretix.event.order.email.error', data={ 'subject': 'SMTP code {}'.format(e.smtp_code), 'message': e.smtp_error.decode() if isinstance(e.smtp_error, bytes) else str(e.smtp_error), 'recipient': '', 'invoices': [], } ) raise SendMailException('Failed to send an email to {}.'.format(to)) except Exception as e: if order: order.log_action( 'pretix.event.order.email.error', data={ 'subject': 'Internal error', 'message': str(e), 'recipient': '', 'invoices': [], } ) logger.exception('Error sending email') raise SendMailException('Failed to send an email to {}.'.format(to))
def send_mail(subject, email_template_name, context, from_email, to_email, verified, cc_list=None, bcc_list=None): """ :param subject: string :param email_template_name: string :param context: string :param from_email: mail id :param to_email: mail id or list of mail ids :param verified: string :param cc_list: mail id or list of mail ids :param bcc_list: mail id or list of mail ids :return: """ mfrom = settings.DEFAULT_FROM_EMAIL if verified: mail_sender = settings.MAIL_SENDER else: mail_sender = settings.INACTIVE_MAIL_SENDER htmly = loader.get_template(email_template_name) html_content = htmly.render(context) recipients = [to_email] if isinstance(to_email, list): recipients = to_email ccs = list() if cc_list: ccs = [cc_list] if isinstance(cc_list, list): ccs = cc_list bccs = list() if bcc_list: bccs = [bcc_list] if isinstance(bcc_list, list): bccs = bcc_list for email in recipients + ccs + bccs: is_valid = validate_email(email, check_mx=True) if not is_valid: raise ValueError("{} is not a valid email".format(email)) if mail_sender == 'AMAZON': client = boto3.client( 'ses', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY) recipients = [to_email] if isinstance(to_email, list): recipients = to_email try: response = client.send_email( Destination={ 'ToAddresses': recipients, 'CcAddresses': ccs, 'BccAddresses': bccs }, Message={ 'Body': { 'Html': { 'Charset': "UTF-8", 'Data': htmly, } }, 'Subject': { 'Charset': "UTF-8", 'Data': subject, }, }, Source=from_email, ) return { 'message': 'Mail sent', 'data': response['ResponseMetadata']['RequestId'] } except ClientError as e: raise e.response['Error']['Message'] elif mail_sender == 'MAILGUN': try: response = requests.post(settings.MGUN_API_URL, auth=('api', settings.MGUN_API_KEY), data={ 'from': mfrom, 'to': recipients, 'subject': subject, "cc": ccs, "bcc": bccs, 'html': html_content, }) return {'message': 'Mail sent', 'data': response.json()} except Exception: raise Exception elif mail_sender == 'SENDGRID': import sendgrid sg = sendgrid.SendGridClient(settings.SG_USER, settings.SG_PWD) sending_msg = sendgrid.Mail() if bcc_list: if isinstance(bcc_list, list): for bcc_mail in bcc_list: sending_msg.add_bcc(bcc_email=bcc_mail) else: sending_msg.add_bcc(bcc_email=bcc_list) if cc_list: if isinstance(cc_list, list): for cc_mail in cc_list: sending_msg.add_cc(cc_email=cc_mail) else: sending_msg.add_cc(cc_email=cc_list) sending_msg.set_subject(subject) sending_msg.set_html(html_content) sending_msg.set_text(subject) sending_msg.set_from(from_email) sending_msg.add_to(to_email) try: response = sg.send(sending_msg) return {'message': 'Mail sent', 'data': response} except Exception: raise Exception elif mail_sender == 'MAILJET': from mailjet_rest import Client API_KEY = settings.MJ_APIKEY_PUBLIC API_SECRET = settings.MJ_APIKEY_PRIVATE mailjet = Client(auth=(API_KEY, API_SECRET), version='v3.1') to_list = list() for recipient in recipients: to_list.append({ "Email": recipient, "Name": ''.join(recipient.split('@')[0].split('.')) }) ccs_list = list() for recipient in ccs: ccs_list.append({ "Email": recipient, "Name": ''.join(recipient.split('@')[0].split('.')) }) bccs_list = list() for recipient in bccs: bccs_list.append({ "Email": recipient, "Name": ''.join(recipient.split('@')[0].split('.')) }) data = { 'Messages': [{ "From": { "Email": from_email, "Name": "Me" }, "To": to_list, "Cc": ccs_list, 'Bcc': bccs_list, "Subject": subject, "HTMLPart": html_content }] } try: result = mailjet.send.create(data=data) return {'message': 'Mail sent', 'data': result.json()} except Exception: raise Exception else: msg = EmailMultiAlternatives(subject, html_content, from_email, recipients, cc=ccs, bcc=bccs) msg.attach_alternative(html_content, "text/html") try: response = msg.send() return {'message': 'Mail sent', 'data': response} except Exception: raise Exception