简体   繁体   English

如何将电子邮件存储在变量中并使用node.js发送

[英]How to store email in variables and send it with node.js

 const functions = require('firebase-functions'); var nodemailer = require('nodemailer'); var transporter=nodemailer.createTransport('smtps://username@gmail.com:password@smtp.gmail.com'); exports.sendMail=functions.https.onRequest((req,res)=>{ var mailOptions={ to: 'sender@gmail.com', subject: 'Test Mail', html: 'Testing with Node.js' } transporter.sendMail(mailOptions,function(err,response){ if(err) { res.send('Mail not sent'); console.log(err); } else{ res.send('Mail sent'); } }); }); 

I want to send email to various persons over time. 我想随着时间的推移向各个人发送电子邮件。 I want to change the to: address in this code dynamically. 我想动态更改此代码中的to:地址。 So how to get a particular(sendermailid) variable from another javascript file and send to that person. 那么如何从另一个JavaScript文件中获取特定(sendermailid)变量并发送给该人。 My folders are located as below the picture. 我的文件夹位于图片下方。 资料夹位置 How to get the variable from assmt.js to index.js(cloud function js). 如何从assmt.jsindex.js(云函数js)获取变量

You need to set up an express server who is listening our other JS aplication like this : 您需要设置一个快速服务器来监听我们的其他JS应用程序,如下所示:

var express  = require('express');
var app      = express();  

Now you can listen from another app on specified port : 现在,您可以从指定端口上的另一个应用程序监听:

var port = process.env.PORT || 8080;
app.listen(port);
console.log("App listening on port " + port);

Finally you have to intercept http post request to send your mail and get user info from the request : 最后,您必须拦截http post请求以发送邮件并从请求中获取用户信息:

app.post('/api/sendmail', function(req, res) {
    var mail = {
                from: req.body.user.emailFrom,
                to: req.body.user.emailTo,
                subject: "your subject",
                html: "<p>email body</p>"
                }



    transporter.sendMail(mail, function(error, response){
                    if(error){
                        console.log("Error!");
                        console.log(error);
                        res.send(JSON.stringify(error));
                    }else{
                        res.send(JSON.stringify(response));
                        console.log("Success!")
                        transporter.close();
                    }

    }

Your server is now ready you can start it with : 现在您的服务器已准备就绪,您可以使用以下命令启动它:

node serverName.js 节点serverName.js

And in your other js file ( assmt.js ) you send the http request with parameter : 然后在另一个js文件(assmt.js)中发送带有参数的http请求:

send(user : User) {
    let body = {user};
     this.httpClient.post('http://localhost:8080/api/sendconge', body)
    .subscribe(function(data) {
            console.log(data);
    });
}

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

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