简体   繁体   中英

How to send email using Angular and Node server?

I am able to send emails with nodejs using nodemailer but my project is in angular 6. I don't know how to integrate that nodejs code into my angular.I just want it for my website contact us forum. Thank you in advance.

You'd need to create a way of allowing your Angular code to talk to your Node.js code, typically you'd use a REST API using Http or Express.

For example, using Express:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 8081;

app.use(bodyParser.json());

// Allow callers to send an email message
app.post('/send_email', function(req, res){
    console.log('send_email body: ',  req.body);
    sendEmail(req.body);
    res.status(201).json({status: 'success' });
});

app.listen(port);

function sendEmail(emailObj) {
    // Send the mail
}

In Angular you can use the HttpClient module to call this, for example:

// Replace the url root as necessary
this.httpClient.post("http://127.0.0.1:8081/send_email",
    {
        "email": "user1@example.com",
        "message": "Test message"
    })
    .subscribe(
        data => {
            console.log("POST Request is successful ", data);
        },
        error => {
            console.log("Error", error);
        }
    ); 

It's worth noting that you will need to provide some authorization mechanism in the REST endpoint (eg POST send_email), since you don't want any old client sending mails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM