如何将ajax联系表单发送到收件人电子邮件地址

时间:2017-09-14 15:08:02

标签: ajax reactjs contact-form

我现在有这个:

$.ajax({
  url: '/some/url',
  dataType: 'json',
  type: 'POST',
  data: formData,
  success: function(data) {
  if (window.confirm('Thank you for your message. Can I erase the form?')) {
   document.querySelector('.form-input').val('');
  }
},
error: function(xhr, status, err) {
  console.error(status, err.toString());
  alert('There was some problem with sending your message.');
}
});

如何将其更改为直接发送到特定的电子邮件地址,而不是转到网址?我正在使用此联系表单与我创建的React应用程序。

1 个答案:

答案 0 :(得分:0)

所以反应组件,基于类。

class Foo extends Component {
    popupQuestion() {
        // implement method
    }
    sendEmail() = () => {
        axios.post('/some/url', {
            subject: 'mail',
            to: 'someone@example.com',
            body: 'something',
            name: 'name'
        })
        .then(function (response) {
            popupQuestion();
        })
        .catch(function (error) {
            console.log(error);
            return 'Error occurred. Please refresh page and try again.';
        });
    }
    render() {
        return(
           <form onSubmit={this.sendEmail}>
               // ...
           </form>
        );
    }
}

将在某些/ url

上执行的php方法
public function sendEmailAction(): bool
{
    $request = // get request;
    $subject = $request->get('subject');
    $to = $request->get('to');
    $body = $request->get('body');
    $name = $request->get('name');
    $transport = (new Swift_SmtpTransport('smtp.example.org', 25))
        ->setUsername('your username')
        ->setPassword('your password');
    $mailer = new Swift_Mailer($transport);
    $message = (new Swift_Message($subject))
        ->setFrom(['mymail@exmaple.com' => 'me'])
        ->setTo([$to => $name])
        ->setBody($body);
    $sent = $mailer->send($message);
    return $sent ? true : false;
}