Home > database >  my email form submit condition not working
my email form submit condition not working

Time:01-13

I have an angular app(contact form) and springboot app which i am using for sending email through gmail when the contact form is submitted.

The issue i am experiencing is that the negative case is not getting captured, in the sense, if my springboot app(email) is down, my angular app still says its success instead of saying "email service is down". Currently what is happening is, in both cases status success is sent, even if the springboot app is down.

Somewhere my condition is not working, any kind of assistance will be really helpful.

my contactus.component.ts file is as below:

import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Loader } from '@googlemaps/js-api-loader';
import { HttpClient } from '@angular/common/http';
import { ReactiveFormsModule } from '@angular/forms';
import * as $ from 'jquery';
import { NgForm } from '@angular/forms';
import { FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-contactus',
  templateUrl: './contactus.component.html',
  styleUrls: ['./contactus.component.css'],
})
export class ContactusComponent implements OnInit {
  formData: FormGroup;
  submitted = false;
  alert: boolean = false;
  pattern = '^[0-9_-]{10,12}';

  constructor(private http: HttpClient, private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.formData = this.formBuilder.group({
      first_name: ['', Validators.required],
      last_name: ['', Validators.required],
      phone: [
        '',
        [
          Validators.required,
          Validators.pattern('^[0-9]*$'),
          Validators.minLength(10),
        ],
      ],
      email: ['', [Validators.required, Validators.email]],
      desc: ['', Validators.required],
    });
  }
  // convenience getter for easy access to form fields
  get f() {
    return this.formData.controls;
  }

  onClickSubmit() {
    this.submitted = true;
    // stop here if form is invalid
    if (this.formData.invalid) {
      return;
    }
    console.log('First Name:'   this.formData.value.first_name);
    console.log('Last Name:'   this.formData.value.last_name);
    console.log('Description:'   this.formData.value.desc);
    console.log('Email:'   this.formData.value.email);
    console.log('Phone Number:'   this.formData.value.phone);

    let mailData = {
      from: '[email protected]',
      subject: 'Enquiry From  Website User',
      body:
        'Hello Admin, \n           You have an Enquiry from a website user, user information is as below: \n\n'  
        '------------------------------------------------------------------------------------'  
        '\n'  
        'First Name : '  
        this.formData.value.first_name  
        '\n'  
        'Last Name : '  
        this.formData.value.last_name  
        '\n'  
        'Description of the Query : '  
        this.formData.value.desc  
        '\n'  
        'Email Address : '  
        this.formData.value.email  
        '\n'  
        'Phone Number : '  
        this.formData.value.phone  
        '\n'  
        '------------------------------------------------------------------------------------\n'  
        'Thank you,\n Admin',
    };

    this.http.post<any>('http://localhost:8084/mail', mailData).subscribe(
      (error) => {
        status = error;
        console.log('status error= '   error.error.text);
        alert('Email Service is down, sorry for inconvenience caused');
      },
      (data) => {
        console.log('status success = '   status);
        this.alert = true;
        alert(
          '\n\nYour Enquiry is Submitted Successfully, we will reach out to you at the earliest !!\n\n\n Thank you,\n Admin'
        );
        //window.location.reload();
      }
    );
  }
}

my mailcontroller file:

package com.sami.EmailClientHMW.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;


@RestController
public class MailController {

    @Autowired
    private JavaMailSender mailSender;
    @GetMapping("/testing")
    public String Testing()
    {
        return "Welcome to HMW Email Client Version..New!!";
    }

    @PostMapping("/mail")
    @CrossOrigin
    public String sendmail(@RequestBody MailRequest request) {
        sendSimpleEmail(request.getFrom(), request.getBody(), request.getSubject());
        return "email sent successfully";
    }

    private void sendSimpleEmail(
            String fromEmail,
            String body,
            String subject)
    {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("[email protected]");
        message.setTo("[email protected]");
        message.setSubject(subject);
        message.setText(body);
            mailSender.send(message);
        System.out.println("Mail Sent Successfully..!!");
    }
}

And my html file :

<div  >
  <div><p align="center">Enter Your Contact Details</p></div>
  <form
    [formGroup]="formData"
    (ngSubmit)="onClickSubmit()"
    data-empty=""
    action="#"
    method="post"
  >
    <div  >
      First Name :
      <input
        type="text"
        formControlName="first_name"
        placeholder="Enter your First Name :"
        
        [ngClass]="{ 'is-invalid': submitted && f.first_name.errors }"
      />
      <div *ngIf="submitted && f.first_name.errors" >
        <div *ngIf="f.first_name.errors.required">First Name is required</div>
      </div>
      <br />
    </div>
    <div  >
      Last Name :
      <input
        type="text"
        formControlName="last_name"
        placeholder="Enter your Last Name :"
        
        [ngClass]="{ 'is-invalid': submitted && f.last_name.errors }"
      />
      <div *ngIf="submitted && f.last_name.errors" >
        <div *ngIf="f.last_name.errors.required">Last Name is required</div>
      </div>
      <br />
    </div>
    <div  >
      Description :
      <textarea
        rows="4"
        cols="90"
        formControlName="desc"
        placeholder="Enter the Description :"
        
        [ngClass]="{ 'is-invalid': submitted && f.desc.errors }"
      ></textarea>
      <!--      <input type="text" formControlName="desc" placeholder="Enter the Description :"  [ngClass]="{ 'is-invalid': submitted && f.desc.errors }" />-->
      <div *ngIf="submitted && f.desc.errors" >
        <div *ngIf="f.desc.errors.required">Description is required</div>
      </div>
      <br />
    </div>
    <div  >
      Email Address :
      <input
        type="text"
        formControlName="email"
        placeholder="Enter your Email Address :"
        
        [ngClass]="{ 'is-invalid': submitted && f.email.errors }"
      />
      <div *ngIf="submitted && f.email.errors" >
        <div *ngIf="f.email.errors.required">Email is required</div>
        <div *ngIf="f.email.errors.email">
          Email must be a valid email address
        </div>
      </div>
      <br />
    </div>
    <div  >
      Phone Number :
      <input
        type="text"
        formControlName="phone"
        placeholder="Enter your Phone Number :"
        
        [ngClass]="{ 'is-invalid': submitted && f.phone.errors }"
      />
      <div *ngIf="submitted && f.phone.errors" >
        <div *ngIf="f.phone.errors.required">Phone Number is required</div>
        <!--        <div *ngIf="f.phone.errors.phone">Enter 10 digit Mobile Number.</div>-->
        <div
          *ngIf="f.phone.errors.pattern || f.phone.errors.maxlength || f.phone.errors.minlength"
        >
          Phone number must be at least 10 numbers
        </div>
      </div>
      <br />
    </div>

    <div >
      <button type="submit" >Submit Your Query</button>
    </div>
  </form>
</div>

CodePudding user response:

Got it..After researching alot on the internet, i was able to get the issue fixed. Below import and inputs i had to include to make it work successfully. Adding here so that if other face same issue, they can have a look at this to fix the issue.

import { HttpHeaders, HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';

let httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', }), responseType: 'text' as 'json' };

this.http.post(environment.apiBaseUrl '/mail',mailData,httpOptions).subscribe

  •  Tags:  
  • Related