0

I want that the user fills a form (made using Django Model Forms) then receive the data from POST and send a copy though gmail using django send_mail function.

Here is my settings.py configuration

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST_USER = 'anyone@gmail.com'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_PASSWORD = ''

Here is my views.py

def GetOrder(request):
    
    mymodalform = MyOrderForm(request.POST)
    
    if mymodalform.is_valid():
        # Save in DB
        mymodalform.save()
        
        # Send a copy via gmail to anyone@gmail.com
        email_subject = 'Order Credentials/Information from ' +  mymodalform.name
        # email_body = "Congratulations if you receive this email, then your order is already in treatment. Below are the order information..." + "Name : " + MyOrderForm.Name + "Phone Number : " + MyOrderForm.Phone + "Email Address : " + MyOrderForm.Email + "Additional Information : " + MyOrderForm.AdditionalInfo + "Ordered pamphlet : " + MyOrderForm.Product + "Number of copies ordered : " + MyOrderForm.Amount 
        #email_body = mymodalform.Product
        from_email = 'anyone@gmail.com'
        to_emails = ['anyone@gmail.com']
        send_mail(
            email_subject,
            mymodalform.split(','),
            from_email,
            to_emails,
            fail_silently=False
        )
        
        # Flash message to confirm order placement.
        messages.add_message(
            request,
            messages.SUCCESS,
            'Your order was placed successfully! We\'ll soon contact you to confirm the order.' 
        )
        
    return redirect('Order')

Here is my forms.py

class MyOrderForm(forms.ModelForm):

   #Metadata
   class Meta:
       model = MyOrderInfo
       fields = [
           'Name',
           'Phone',
           'Email',
           'AdditionalInfo',
           'Product',
           'Amount',
       ]
    
  
    # Definition of widgets
       widgets = {
           'Name': forms.TextInput(
                attrs={
                    'class': 'form-control',
                    'name': 'name',
                    'id': 'name',
                    'placeholder': 'Your Name...'
                }
            ),
           
           'Phone':forms.NumberInput(
                attrs={
                    'class': 'form-control',
                    'name': 'organization',
                    'id': 'organization',
                    'placeholder': 'Your phone number...'
                }
            ),
           
           'Email': forms.EmailInput(
                attrs={
                    'class': 'form-control',
                    'name': 'email',
                    'id': 'email',
                    'placeholder': 'Your Email address...'
                }
            ),
           
           'AdditionalInfo': forms.Textarea(
                attrs={
                    'class': 'form-control',
                    'name': 'message',
                    'id': 'message',
                    'rows': '7',
                    'cols': '30',
                    'placeholder': 'Provide some extra information if any e.g. Your address (precisely), observations, Do you need delivery?, etc'
                }
            ),
           
           'Product': forms.Select(
                choices= CHOICES,
                attrs={
                    'class': 'custom-select',
                    'id': 'budget',
                    'name': 'budget'
                }
            ),
           
           'Amount': forms.NumberInput(
                attrs={
                    'class': 'form-control',
                    'name': 'date',
                    'id': 'date',
                    'placeholder': 'Number of copies...'
                }
            )
       }

Need help on how to get the data through POST and then email it to anyone@gmail.com. Thanks

Joel Fah
  • 36
  • 4
  • that looks like it should work ... what part isnt working? – Joran Beasley Jul 03 '21 at 07:06
  • 1
    @JoranBeasley. It works but the OP probably wants to load a template `django.template.loader.get_template()`, pass `mymodalform` as context and `render` the ouput as `email_body`. – Corralien Jul 03 '21 at 07:10

1 Answers1

0

just make a form and then in your views (like another form that saves data to database) after form.is_valid() get values from field data and then send the email.

@login_required
def sendmail(request):
    if request.method == 'POST':   
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message'] + ' ' + "|| Senders email: " + f'{email}'

            try:
                send_mail(
                    name, #subject
                    message, #message
                    email, #from email
                    ['sitemail.geo@gmail.com'], #to email
                    )
            except BadHeaderError:
                return httpResponse('Invalid header found')
            messages.success(request, f'Thanks {name}! We received your email and will respond shortly...') 
            return redirect('home') 
    else:
        form = ContactForm()        
    return render(request, 'sendmail/mail.html', {'form': form}) 
NickNaskida
  • 106
  • 7