简体   繁体   English

如何使用Angular和Node服务器发送电子邮件?

[英]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. 我可以使用nodemailer发送带有nodejs的电子邮件,但我的项目在angular 6中。我不知道如何将nodejs代码集成到我的angular.I中,我只想在我的网站上与我们联系。 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. 您需要创建一种允许Angular代码与Node.js代码对话的方法,通常,您需要使用Http或Express的REST API。

For example, using Express: 例如,使用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: 在Angular中,您可以使用HttpClient模块来调用它,例如:

// 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. 值得注意的是,由于您不希望任何旧客户端发送邮件,因此您需要在REST端点中提供某种授权机制(例如POST send_email)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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