javascript 如何使用Vuejs发送电子邮件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49149550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:26:42  来源:igfitidea点击:

how to send an email with Vuejs?

javascriptformsemailvue.js

提问by DenisMasot

How can I do to send an email with Vuejs2. I manage to get the input data and turned them into json but I can not send them to a mailbox.

如何使用 Vuejs2 发送电子邮件。我设法获取输入数据并将它们转换为 json,但我无法将它们发送到邮箱。

I look for the side of PHPMailer but facing PHP and Vue do not mix.

我寻找PHPMailer的一面,但面对PHP和Vue不混合。

How can I send the form content?

如何发送表单内容?

Template :

模板 :

 <div class="JC-contact__form">
  <b-form @submit="onSubmit" v-if="show">

    <b-form-group class="JC-contact__form--lastName">
      <b-form-input type="text" v-model="form.lastName"> </b-form-input>
    </b-form-group>

    <b-form-group class="JC-contact__form--firstName">
      <b-form-input type="text" v-model="form.firstName"> </b-form-input>
    </b-form-group>

    <b-form-group>
      <b-form-input type="text" v-model="form.topic"> </b-form-input>
    </b-form-group>
    <b-form-group>
      <b-form-input type="email" v-model="form.email"></b-form-input>
    </b-form-group>

    <b-form-textarea v-model="form.text"></b-form-textarea>

    <b-button type="submit">Envoyer</b-button>
  </b-form>

</div>

Script :

脚本 :

  export default {
    name: 'Contact',
    data () {
      return {
        form: {
          lastName: '',
          firstName: '',
          topic: '',
          email: '',
          text: ''
        },
        file: null,
        show: true
      }
    },
    methods: {
      onSubmit (evt) {
        evt.preventDefault();
        alert(JSON.stringify(this.form));
      },
      onReset (evt) {
        evt.preventDefault();
        /* Reset our form values */
        this.form.lastName = '';
        this.form.firstName = '';
        this.form.topic = '';
        this.form.email = '';
        this.form.text = '';
        /* Trick to reset/clear native browser form validation state */
        this.show = false;
        this.$nextTick(() => {
          this.show = true
        });
      }
    }
  }

回答by Imre_G

Sending mail from Vue directly is not possible as you need some sort of server to handle the mail protocol. This can never be done directly from the browser. I am not familiar with PHP, so I can't help you with that. In node you need the nodemailer package and some smtp server to handle the email like Amazon Simple Email Server (or you could use your gmail account). What you could also do is use axios to send a post request to SendGrid or Mandrill or some service like that. They will convert your request to an email and send it to an address specified in you request body.

直接从 Vue 发送邮件是不可能的,因为您需要某种服务器来处理邮件协议。这永远不能直接从浏览器完成。我不熟悉 PHP,所以我不能帮你。在 node 中,您需要 nodemailer 包和一些 smtp 服务器来处理电子邮件,例如 Amazon Simple Email Server(或者您可以使用您的 gmail 帐户)。您还可以使用 axios 向 SendGrid 或 Mandrill 或类似服务发送 post 请求。他们会将您的请求转换为电子邮件并将其发送到您在请求正文中指定的地址。

More info here:

更多信息在这里:

https://sendgrid.com/docs/API_Reference/Web_API/mail.html

https://sendgrid.com/docs/API_Reference/Web_API/mail.html

https://mandrillapp.com/api/docs/

https://mandrillapp.com/api/docs/

回答by Yako

This is how I did:

这就是我所做的:

Mailing from the server side

从服务器端邮寄

The PHP mail()function will just work fine. Nothing fancy here.

PHPmail()函数将正常工作。这里没什么好看的。

mail.php- This one must be located somewhere accessible on your server.

mail.php- 这个必须位于您服务器上可访问的某个地方。

<?php

$name = "Undefined name";

if(isset($_POST['name'])){
    $name = $_POST['name'];
}

$message = "<p>Hi!</p>";
$message .= "<p>Wazaaaaa $name</p>";

$to_email = '[email protected]';
$subject = 'Mail subject';
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=UTF-8';
$headers[] = 'From: Biloo <[email protected]>';

mail($to_email, $subject, $message, implode("\r\n", $headers));

?>

Be aware that headers values must be trustworthy(no unverified user-submited values).

请注意,标头值必须值得信赖(没有未经验证的用户提交值)。



Sending data to the mailing script

将数据发送到邮件脚本

Then VueJS is suppposed to send the appropriate data to the mailing script:

然后 VueJS 应该将适当的数据发送到邮件脚本:

components/Mail.vue

components/Mail.vue

<template>
   <div>
      <transition name="fade" mode="out-in">
          <div v-if="sent">
              <p>Thanks</p>
          </div>
      </transition>
      </div>
      <div v-if="!sent" class="formGroup">
          <b-form @submit="onSubmit">
              <b-form-input
                  id="input-name"
                  v-model="form.name"
                  type="text"
                  required
                  placeholder="Name"
              />
              <b-button type="submit">
                  Contact
              </b-button>
          </b-form>
      </div>
   </div>
</template>

<script>
const querystring = require("querystring");

export default {
    data() {
        return {
          sent: false,
          form: {
              name: ""
          }
        };
    },
    methods: {
      onSubmit(e) {
          e.preventDefault();
          this.$axios
             .post(
                 "https://theServer.com/mail.php",
                  querystring.stringify(this.form)
             )
             .then(res => {
                 this.sent = true;
             });
      }
    }
};
</script>

Here, it is important to note that the default behavior of Axios is to post a JSON object. However, doing so, PHP will receive an empty $_POSTvalue. Data must therefore be formatted using the querystringdependency before being posted.

这里需要注意的是,Axios 的默认行为是发布一个 JSON 对象。但是,这样做,PHP 将收到一个空$_POST值。因此,必须querystring在发布之前使用依赖项对数据进行格式化。

Querystring can be installed with npm:

查询字符串可以通过 npm 安装:

npm i querystring

npm i querystring

回答by Gbadamosi Moshood

<template>    
<div class="request-a-callback-form">
 <transition name="fade" mode="out-in">
  <div v-if="sent">
   <p>Thanks for contacting us, we will get back to you shortly...</p>
  </div>
 </transition>
 <form v-on:submit="sendForm">
  <input type="text" v-model="ContactForm.name" placeholder="Your Name">
  <input type="text" v-model="ContactForm.email" placeholder="Email Address">
  <input type="text" v-model="ContactForm.phone" placeholder="Phone Number">
  <input type="text" v-model="ContactForm.subject" placeholder="Subject">
  <textarea v-model="ContactForm.message" rows="8" cols="80" class="form-control"> 
  </textarea>
  <br>
  <button data-text="submit" type="submit" class="btn btn-primary">Submit</button>
 </form>
</div>
</template>
        <script>
        export default {
          data() {
            return {
              sent: false,
              ContactForm: {
                name : '',
                email: '',
                phone: '',
                subject: '',
                message: ''
              }
            }
          },
          methods: {
            sendForm(e) {
              e.preventDefault()
              console.log(this.ContactForm)
              this.$axios.post('api/mailserver.php',
              querystring.stringify(this.ContactForm)).then(res => {
                this.sent = true
              })
            }
          }
        }
        </script>

    Your php Server

    <?php
    // Allow from any origin
     if(isset($_SERVER["HTTP_ORIGIN"]))
     {
        // You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to 
      allow, or as we do here, just allow all
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
     }
     else
     {
        //No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
        header("Access-Control-Allow-Origin: *");
     }

     header("Access-Control-Allow-Credentials: true");
     header("Access-Control-Max-Age: 600");    // cache for 10 minutes

     if($_SERVER["REQUEST_METHOD"] == "OPTIONS")
     {
        if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"]))
            header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); 
  //Make 
        sure you remove those you do not want to support

        if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))
            header("Access-Control-Allow-Headers: 
           {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

           //Just exit with 200 OK with the above headers for OPTIONS method
        exit(0);
      }
    //From here, handle the request as it is ok


     if(!empty($_POST['name'])){
        $name = $_POST['name'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $subject = $_POST['subject'];
        $message = $_POST['message'];
     }

     $message = "$message";

     $to_email = '<email to be sent to>';
     $subject = "$subject";
     $headers[] = 'MIME-Version: 1.0';
     $headers[] = 'Content-type: text/html; charset=UTF-8';
     $headers[] = "From: <$email>";

     mail($to_email, $subject, $message, implode("\r\n", $headers));

    ?>