hellp:在Django中发送大量电子邮件

时间:2016-01-06 22:36:51

标签: python django email

我有一个应用程序通过smtp发送邮件。它工作正常,并在3-4秒内发送邮件。我希望他发送(批量电子邮件)。 你能帮我吗?

views.py

    # -*- coding: utf-8 -*-
from __future__ import absolute_import
# import json
import smtplib
from django.views.generic import TemplateView, View
from django.views.generic.edit import UpdateView
from django.shortcuts import get_object_or_404, redirect
from django.core.urlresolvers import reverse_lazy
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from braces.views import LoginRequiredMixin
from .forms import ServerForm, SettingForm, MailerForm
from .models import Server, Setting
from .tasks import sender


class HomeView(LoginRequiredMixin, TemplateView):
    template_name = 'core/home.jinja'

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        context['form'] = MailerForm(initial={'headers': '{}'})
        return context

    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        form = MailerForm(request.POST, request.FILES)
        if form.is_valid():

            sender_name = form.cleaned_data['sender_name']
            sender_email = form.cleaned_data['sender_email']
            mail_list = form.cleaned_data['mail_list']
            subject = form.cleaned_data['subject']
            encoding = form.cleaned_data['encoding']
            headers = form.cleaned_data['headers']

            message = form.cleaned_data['message']

            servers = Server.objects.all()
            configuration = Setting.objects.first()

            email_number = configuration.email_number
            time_delay = configuration.time_delay

            # Parsing the email list and spliting it by configured emails
            # number
            recipients = [l.strip() for l in mail_list.readlines()]
            splitted_emails = [list(recipients[i:i + email_number])
                               for i in range(0, len(recipients), email_number)]

            sender.delay(sender_name, sender_email, splitted_emails,
                         servers, subject, message, encoding, headers, time_delay)

        context['form'] = form
        return self.render_to_response(context)

tasks.py

 # -*- coding: utf-8 -*-
from __future__ import absolute_import
import time
import uuid
from django.core.mail import EmailMessage
from django.template import Context, Template
from celery.decorators import task
from app.utils import get_next_server, smtp_connection
from app.core.encoders import encode_base64, qpencode, encode_quopri
# from django.core.mail import send_mail


@task(name="Sending Emails")
def sender(sender_name, sender_email, splitted_emails, servers, subject, message, encoding, headers, dt,):
    s = get_next_server(servers)


    for l in splitted_emails:
        server = s.next()
        print server.host, server.port
        # if server.status:
        message = Template(message).render(Context({'link': str(uuid.uuid4())}))
        connection = smtp_connection(server)
        for email in l:
            print "Sending to {}".format(email)

            mail = EmailMessage(
                subject,
                message,
                "{} <{}>".format(sender_name, sender_email),
                [email, ],
                connection=connection,
                headers=headers,
            )


            mail.content_subtype = 'html'
            mail.send(fail_silently=False)
        connection.close()
你能帮我吗? 你能帮我吗?

1 个答案:

答案 0 :(得分:0)

尝试使用此处记录的send_mailsend_mass_mailhttps://docs.djangoproject.com/en/1.9/topics/email/

电子邮件数组有一个参数。 send_mass_mail甚至会使用一个连接发送所有邮件,这似乎就是你想要的。