首页 文章

Angular 4和PHP电子邮件发送

提问于
浏览
0

我试图从php发送函数发送电子邮件,它正在发送一封电子邮件,但没有用任何数据填充它,它是null

我的代码这是Angular中的发送服务 . 在这里,我的消息包含了我表格中的所有数据

export interface IMessage {
  name?: string,
  telephon?: string,
  message?: string
}

@Injectable()
export class AppService {
  private emailUrl = '../assets/contact.php';

  constructor(private http: Http) {

  }

  sendEmail(message: IMessage): Observable<IMessage> | any {
    JSON.stringify(message);   // also tried without it
    return this.http.post(this.emailUrl, message)
      .map(response => {
        console.log('Sending email was successfull', response);
        return response;
      })
      .catch(error => {
        console.log('Sending email got error', error);
        return Observable.throw(error)
      })
  }
}

PHP代码

<?php
    header('Content-type: application/json');
    $errors = '';
    if(empty($errors))
    {
        $postdata = file_get_contents("php://input"); // here I have null
        $request = json_decode($postdata);  // here I have null checked in console
        $from_email = $request->email;
        $message = $request->message;
        $from_name = $request->name;
        $to_email = 'myEmail@gmail.com';

        $contact = "<p><strong>Name:</strong> $from_name</p>
                                <p><strong>Email:</strong> $from_email</p>";
        $content = "<p>$message</p>";
        $website = 'My Wicked Awesome Website';
        $email_subject = "$website: Received a message from $from_name ";

        $email_body = '<html><body>';
        $email_body .= "$contact $content";
        $email_body .= '</body></html>';

        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        $headers .= "From: $from_email\n";
        $headers .= "Reply-To: $from_email";

        mail($to_email,$email_subject,$email_body,$headers);
        $response_array['status'] = 'success';
        $response_array['from'] = $from_email;
        $response_array['MESSAGE'] = $message;
        $response_array['POSTDATA'] = $postdata;
        $response_array['REQUEEST'] = $request;
        e

cho json_encode($response_array);
    echo json_encode($from_email);
    header($response_array);
    return $from_email;
} else {
    $response_array['status'] = 'error';
    echo json_encode($response_array);
    header('Location: /error.html');
}
?>

有什么想法?谢谢

2 回答

  • 0

    你只需要在php中获取发布数据

    更改

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

    $message = $_POST['message'];
    
  • 0

    我建议定义变量:

    // JS - remove JSON.stringify
    sendEmail(message: IMessage): Observable<IMessage> | any {
        return this.http.post(this.emailUrl, message)
        ...
    
    // PHP
    $message = filter_input('message', '', FILTER_SANITIZE_STRING);
    $from_name = filter_input('name', '', FILTER_SANITIZE_STRING);
    

相关问题