Thursday 2 May 2019

django 32 sending email

dynamically add/remove recipients

all recipients receive email


#urls
from django.urls import path
from . import views

app_name = 'music'

urlpatterns = [
#music/eamil
    path('email/', views.Email.as_view(), name='email'),
]

-------------------------------------
#views

from .forms import SendEmailForm
from django.contrib import messages
from django.core.mail import send_mail
from django.conf import settings

class Email(View):
    form_class = SendEmailForm
    template_name = 'music/email_form.html'

    def get(self, request):
        #get request, display Form with empty fields
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():
            subject = form.data['subject']
            message = form.data['message']
            email_from = settings.EMAIL_HOST_USER
            recipient_list = request.POST.getlist('recipients[]')
            send_mail(subject, message, email_from, recipient_list)

            messages.success(request, 'emails sent')
            return redirect('music:email')

        messages.error(request, 'error')
        return render(request, self.template_name, {'form': form})

----------------------------------------
#forms

class SendEmailForm(forms.Form):
    subject = forms.CharField(widget=forms.TextInput())
    message = forms.CharField(widget=forms.Textarea, required=False)

-------------------------------------------
#settings

#email setting
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'zchen2014chuanshuo@gmail.com'
EMAIL_HOST_PASSWORD = 'xxx'

-------------------------------------------
#template/email_form

{% extends 'music/base.html' %}
{% block title %}Email{% endblock %}
{% load crispy_forms_tags %}

{% block body %}
    <div class="container-fluid">

        <div class="row">

            <div class="col-sm-12 col-md-7">

                <form  action="" method="post" enctype="multipart/form-data">
                    {% csrf_token %}
                    <fieldset class="form-group">
                        <legend class="border-bottom mb-4">Send Email</legend>
                    </fieldset>
                    <div class="input_fields_wrap form-group">
                        <label>Recipients</label>
                        <button class="add_field_button btn-outline-dark">Add more</button><br>
                        <input type="email" name="recipients[]" required="required">
                    </div>
                    <div class="form-group">
                        {{ form|crispy }}
                    </div>
                    <div class="form-group">
                        <button class="btn btn-success btn-sm" type="submit">Submit</button>
                    </div>
                </form>

            </div>
        </div>
    </div>

<script type="text/javascript">
$(document).ready(function() {
var max_fields      = 10; //maximum input boxes allowed
var wrapper    = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="email" name="recipients[]" required="required"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>

{% endblock %}

------------------------------------------
#templates/base

<body>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
....
</body>

reference:
http://chuanshuoge2.blogspot.com/2019/04/django-32-sending-email.html

No comments:

Post a Comment