Django

How to Django Send Email with Attachment – Django

Pinterest LinkedIn Tumblr

How to Django Send Email with Attachment – Django

Setup Gmail Account for Email API

Configure Django for Gmail SMTP server

Go to your settings.py file and add the following parameters

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER='gmail@gmail.com'
EMAIL_HOST_PASSWORD='passs!@#$%'

Open your html form and put code

<form action="{% url 'contact_mail' %}" method="post">
             {% csrf_token %}
              <div class="form-group">
               <select class="form-control" name="topic" required>
                  <option>Topic*</option>
                  <option value="New Customer">New Customer</option>
                  <option>Employment</option>
                  <option>Existing Customer
                  </option>
                  <option>Partner</option>
                  <option>Supplier</option>
                  <option>Other</option>
               </select>
            </div>
           <div class="form-group">
              <textarea class="form-control txtarea" rows="4"  name="message" placeholder="Message*" required></textarea>
           </div>
          
           
         <div class="form-group">
           <input type="text" class="form-control" name="lastname" placeholder="Last Name*">
         </div>
         <div class="form-group">
               <input type="email" class="form-control" name="email" placeholder="Email*">
            </div>
          <div class="form-group">
               <input type="text" class="form-control" name="phone_number" placeholder="Phone Number">
            </div>
            <div class="submit_btn">
                <input type="submit" name="submit" class="commoncta" value="SUBMIT">
          </div>
         </form>

Open your views and put function inside of views.py

def contact_mail(self, form,request):
        subject = forms.CharField(max_length=100)
    if(request.POST):
        subject = "Lead from Realprogrammer"
        to = "siddharthshukla089@gmail.com"
        contact_form = request.POST.dict()
        topic = contact_form.get("topic")
        message = contact_form.get("message")
        firstname = contact_form.get("firstname")
        email = contact_form.get("email")
        phone_number = contact_form.get("phone_number")
        html_template = "testmail.html"
        html_message = render_to_string(html_template,{'topic': topic, 'message': message, 'firstname': firstname, 'email': email, 'phone_number': phone_number})
        message = EmailMessage(subject, html_message, settings.EMAIL_HOST_USER, [to])
        message.content_subtype = 'html' # this is required because there is no plain text email message
        message.send()
        return HttpResponse('success')

Open urls.py

from django.urls import path

from .views import *

urlpatterns = [
path('contact_mail', contact_mail, name='contact_mail')]