'API is working in POSTMAN but post method is not during send mail in ANGULAR

I am developing AspNETCoreAPI/Angular project. I am trying to send mail and its working in backend. But in frontend, it is not. I can get the datas and controlled in console.

Here is the postman 'OKAY' result.

Here is the debug result

MailRequest service.cs

public async Task SendEmailAsync(MailRequest mailRequest)
        {
            var email = new MimeMessage();
            email.Sender = MailboxAddress.Parse(_mailSettings.Mail);
            email.To.Add(MailboxAddress.Parse(mailRequest.ToEmail));
            email.Subject = mailRequest.Subject;
            var builder = new BodyBuilder();
            if (mailRequest.Attachments != null)
            {
                byte[] fileBytes;
               foreach (var file in mailRequest.Attachments)
                {
                    if (file.Length > 0)
                    {
                        using (var ms = new MemoryStream())
                        {
                            file.CopyTo(ms);
                            fileBytes = ms.ToArray();
                        }
                        builder.Attachments.Add(file.FileName, fileBytes, ContentType.Parse(file.ContentType));
                    }
                }
            }
            builder.HtmlBody = mailRequest.Body;
            email.Body = builder.ToMessageBody();
            using var smtp = new SmtpClient();
            smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls);
            smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password);
            await smtp.SendAsync(email);
            smtp.Disconnect(true);
        }

mail.service.ts

import { HttpClient, HttpErrorResponse, HttpHeaders } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { observable, Observable } from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class MailService {

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

  contactForm = this.fb.group({
    ToEmail:[''],
    Attachments: null,
    Subject:[''],
    Body:['']
  });
  sendEmail(){
    var request = { 
      ToEmail: this.contactForm.value.ToEmail,
      Attachments: this.contactForm.value.Attachments,
      Subject: this.contactForm.value.Subject,
      Body: this.contactForm.value.Body, };
     var headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');

    return this.http.post<any>('http://localhost:5000/api/mail/send',JSON.stringify(request),{headers: headers});
  }

mail.component.ts

export class SendmailComponent implements OnInit {


  public submitted: boolean;


  constructor(public mailservice:MailService) { }



  onSubmit(){
    this.mailservice.sendEmail().subscribe((res:any) => {
      console.log("ok");
    },
    err => {
      if (err.status === 500)
        console.log("error");
    }
    );
    // console.log(value, valid);
  }



  ngOnInit() {
    this.mailservice.contactForm.reset();
  }
 
}

mail.component.html

<nb-card>
    <nb-card-body class="bodyy">
        <form [formGroup]="mailservice.contactForm" (submit)="onSubmit()">
            <div class="form-group">
              <label>Email</label>
              <input  type="text" formControlName="ToEmail" class="form-control" placeholder="Enter email">
              <div [hidden]= "mailservice.contactForm.controls.ToEmail.valid || mailservice.contactForm.controls.ToEmail.pristine" class="alert alert-danger">
                <span *ngIf="!mailservice.contactForm.controls.ToEmail.valid"> Email is required!</span>
              </div>
            </div>
            <div class="form-group">
              <label>Subject</label>
              <input  type="text" formControlName="Subject" class="form-control" placeholder="Enter subject">
              <div [hidden]= "mailservice.contactForm.controls.Subject.valid || mailservice.contactForm.controls.Subject.pristine" class="alert alert-danger">
                <span *ngIf="!mailservice.contactForm.controls.Subject.valid"> Subject is required!</span>
              </div>
            </div>
            <div class="form-group">
              <label>Message</label>
              <textarea rows="3" type="text" formControlName="Body" class="form-control" placeholder="Enter message"></textarea>
              <div [hidden]= "mailservice.contactForm.controls.Body.valid || mailservice.contactForm.controls.Body.pristine" class="alert alert-danger">
                <span *ngIf="!mailservice.contactForm.controls.Body.valid"> Message is required!</span>
              </div>
            </div>
            <div class="form-group">
                <label>Attachments</label>
                <input type="file" formControlName="Attachments" placeholder="Add something"/>
            </div>
            <br>
            <button type="submit" class="btn btn-primary" [class.btn-pulse]="submitted">Submit</button>
        </form>
    </nb-card-body>
</nb-card>

Thank you in advance !



Solution 1:[1]

it seems that your body is sent as a json object while your API is expecting a formdata object (see MDN using form data try building your body as suggested in the link above, it should be ok then!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eikichie