将多个收件人电子邮件和姓名附加到EmailMultiAlternatives

时间:2015-07-09 23:09:08

标签: python django email-integration mandrill

您好我有一个表单mixin,用户输入一条消息并将其发送给多个收件人。我使用Mandrill作为我的电子邮件客户端。我目前能够将电子邮件发送给单个收件人,但在输入多个用户时失败。

这是形式mixin

class FormListView(FormMixin, ListView):
    def get(self, request, *args, **kwargs):
    form_class = self.get_form_class()
    self.form = self.get_form(form_class)
    self.object_list = self.get_queryset()
    context = self.get_context_data(object_list=self.object_list, form=self.form)
    return self.render_to_response(context)

class CardListNew(FormListView):
    form_class = EmailForm
    model = card

    def get_queryset(self):

    return card.objects.filter(pk__in=[1]).filter(is_published='true')

def sendmail(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
           fullname = form.cleaned_data['name']
           email = form.cleaned_data['email']
           rname = form.cleaned_data['rname']
           remail = form.cleaned_data['remail']
           subject = "You received an email from " +  fullname
           message = form.cleaned_data['message']
           connection = get_connection()
           connection.open()
           text_content =  message

           msg = EmailMultiAlternatives(subject, message, email, [remail])
           template_data = {
                         'sender_name': fullname, 'sender_email': email, 'receiver_name': rname, 'receiver_email': remail, 'message': message
        }
           html_content = render_to_string("email.html", template_data)
           msg.attach_alternative( html_content , "text/html")
           msg.send()
           connection.close() # Cleanup
           return HttpResponseRedirect('/thank-you/')
   else:
       form = EmailForm()

   return render(request, 'card.html')  

这是提交电子邮件的表单。我目前使用相同的输入名称作为接收方电子邮件和接收方名称。

<form role="form" action="/sendmail/" method="post">

<input type="text" name="name" class="form-control input" id="input1" autocomplete="off" placeholder="Enter Name">

<input type="text" name="email" class="form-control input" id="input2" autocomplete="off" placeholder="Enter Email">

<input class='form-control reciptest' name="rname" placeholder='Recipient Name' type='text'>

<input type="text" class="form-control emailtest" name="remail" placeholder="Recipient Email">

<a  class="btn btn-sm btn-default" onClick="addInput('dynamicInput');">Add Recipient </a>
<a class="btn btn-sm btn-default" onClick="removeInput('dynamicInput');">Remove Recipient</a>

<textarea id="input3" name="message" class="form-control input" rows="6" placeholder="Not more than 1000 letters" maxlength="1000"></textarea>

我如何分割和匹配列表收件人姓名和电子邮件,并将其附加到EmailMultiAlternatives()和template_data?

1 个答案:

答案 0 :(得分:0)

EmailMultiAlternatives为“to”参数提供了一个电子邮件地址列表,因此可以采用简单的方法进行更改:

yarn-cluster

为:

   msg = EmailMultiAlternatives(subject, message, email, [remail])

将每个逗号分隔remail字段的文本到列表中。