Sending Email from Angular 2

前端 未结 2 1770
北荒
北荒 2020-12-31 18:03

How Do I Send Email from an Angular 2 App?

I am hosting an Angular 2 app on firebase. I want to send a contact form as an email. Ideally my solution would use Nodej

相关标签:
2条回答
  • 2020-12-31 18:29

    Edit: I just saw that you are serving on Firebase, I will look into how that changes things.

    How would I run server-side code in Firebase?

    Angular 2 is client side, if you want to do make an API call w/ your secret you should probably be doing it server side, aka node.js or whatever your server is.

    Because you have sendmail.js as a script, consider serving your Angular 2 application with node.js and having an API endpoint with express, like /api/sendMail that you can make an XHR/AJAX request to from your Angular 2 application.

    0 讨论(0)
  • 2020-12-31 18:30

    try to rewrite your sendmail.js as rest service, for example:

    const Sendgrid = require('sendgrid')(
      process.env.SENDGRID_API_KEY || '<my-api-key-placed-here>'
    );
    
    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    
    app.post('/send-mail', function (req, res) {
      // PUT your send mail logic here, req.body should have your fsubmitted form's values
      sendMail(req.body);
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "X-Requested-With");
      res.send('SEND MAIL');  
    })
    
    app.listen(3000, function () {
      console.log('LISTENING on port 3000');
    })
    
    
    function sendMail(formData) { 
      let request = Sendgrid.emptyRequest({
        method: 'POST',
        path: '/v3/mail/send',
        body: {
          personalizations: [{
            to: [{ email: 'my.email@gmail.com' }],
            subject: 'Sendgrid test email from Node.js'
          }],
          from: { email: 'noreply@email-app.firebaseapp.com' },
          content: [{
            type: 'text/plain',
            value: `Hello ${formData.userFirstName} ${formData.userLastName}! Can you hear me ${formData.userFirstName}?.` 
          }]
        }
      });
    
      Sendgrid.API(request, function (error, response) {
        if (error) {
          console.log('Mail not sent; see error message below.');
        } else {
          console.log('Mail sent successfully!');
        }
        console.log(response);
      });
    }
    

    please note, that I used form data within email's body

    then in your submit function in angular, just execute

    http.post('http://localhost:3000/send-mail', this.contactForm.value);
    
    0 讨论(0)
提交回复
热议问题