1

I have created a simple app with third party email sending api implementation to get email through contact form. When I am running the app on my local host or on my github page, I am getting this error:

Access to XMLHttpRequest at 'https://api.mailjet.com/v3.1/send' from origin 'https://myrepo.github.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What is the solution for that issue. Obviously I can't apply any solution in API end, all I have to do is from my angular code. Here is what I have implemented in my http post request

sendMail(): Observable<any>{
    let API_URL='https://api.mailjet.com/v3.1/send';
    let data={
      "Messages":[
        {
          "From": {
            "Email": "myemail@gmail.com",
            "Name": "My Name"
          },
          "To": [
            {
              "Email": "myemail@gmail.com",
              "Name": "My Name"
            }
          ],
          "Subject": "My first Mailjet email",
          "TextPart": "Greetings from Mailjet.",
          "HTMLPart": "<h3>Dear passenger 1, welcome to <a href=https://www.mailjet.com/>Mailjet</a>!</h3><br />May the delivery force be with you!",
          "CustomID": "AppGettingStartedTest"
        }
      ]
    };
    console.log('sending email....')
    console.log(data);
    this.httpClient.post<any>(API_URL,data,{
      headers: new HttpHeaders({
        'Content-Type':'application/json',
        'Authorization':'Basic VGIzOTIsasdasdasdasdasdrewetwfdsfasdasMjI0NWUVcDFGA='
      })
    }).subscribe(res=>{
      console.log(res);
    },err=>{
      console.log(err);
    });
    return null;//ignoring this for now.

  }
jhon
  • 101
  • 11
  • 1
    I guess it is the whole point of CORS that you cannot work around on the client side only. – Henry Jan 02 '21 at 06:52
  • I know I can bypass this by running chrome with the cors disable option. But that's not the ultimate solution. Also, mailjet is providing a functional api, so I can't say their API is not working. Their API is working from postman as well. – jhon Jan 02 '21 at 06:54

3 Answers3

2

You can't. You have to use a server side implementation like PHP, because as far as I know you can't send emails through client side with mailjet. It's not secure either as you have to mention your API key in the Angular app. Imagine if someone reverses engineer your Angular app, and read your API key?. Send a request to your PHP file through the following Typescript function in a service file in Angular. Make sure to specify its URL as well. The Content has three properties, email, subject, and message. You have to assign values to them before passing them to the parameter of the sendEmail function.

Client Side Implementation

  public sendEmail(content: object): Observable<any> {
    return this.httpClient.post(this.SMTPURL, JSON.stringify(content));
  }

Server Side Implementation

<?php 

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

function sanitizeEmail($email) {
    return filter_var($email, FILTER_SANITIZE_EMAIL);
}

function sanitizeMessage($message) {
    return filter_var($message, FILTER_SANITIZE_STRING);
}

function sanitizeSubject($subject) {
    return  filter_var($subject, FILTER_SANITIZE_STRING);
}

if($request->request) {
    $to_email = sanitizeEmail($request->email);
    $subject = sanitizeSubject($request->subject);
    $message = sanitizeMessage($request->message);
    mail($to_email, $subject, $message);    
    echo json_encode("Email was sent to " . $to_email . "\n " . $subject . "\n " . $message);
} else {
    echo 'Unable to Handle the request';
}


?>
Don Dilanga
  • 2,722
  • 1
  • 18
  • 20
0

I think you should config your web server to proxy that or use Configure Angular CLI proxy for development.

Arash Hatami
  • 522
  • 4
  • 10
0

According to this question it is better to have a server-side funtion that talks to you APIs. I don't know if it's your case, but it could work