gpt4 book ai didi

javascript - Nodejs和Nodemailer接收用户ip地址?

转载 作者:行者123 更新时间:2023-12-02 21:05:37 24 4
gpt4 key购买 nike

您好,我想回显此命令request.connection.remoteAddress在 Node.js 中 |回显用户 IP 地址有人可以帮忙吗

我正在尝试使用此代码通过nodemailer接收联系电子邮件

const bodyParses = require('body-parser');
const exphbs = require('express-handlebars');
const path = require('path');
const nodemailer = require('nodemailer');

const app = express();



// View engine setup
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// Main Folder
app.use('/public', express.static(path.join(__dirname, 'public')));
//Body Parses Middleware
app.use(bodyParses.urlencoded({ extended: false}));
app.use(bodyParses.json());


app.get('/', (req, res) => {
res.render('contact', {layout: false});
});

app.post("/send", async (req,res,next) => {
const output = `
<p>You have a new contact requiest</p>
<h3>Detajet</h3>
<ul>
<li>Name: ${req.body.name}</li>
<li>Comapny: ${req.body.company}</li>
<li>Email: ${req.body.email}</li>
<li>Phone: ${req.body.phone}</li>
<li>${res.send(ip+"\n")}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: 'user@gmail.com', // generated ethereal user
pass: 'password' // generated ethereal password
},
tls:{
rejectUnauthorized:false
}
});

// send mail with defined transport object
let info = await transporter.sendMail({
from: '"Tipi" <aj.production15@gmail.com>', // sender address
to: "test@gmail.com", // list of receivers
subject: "test", // Subject line
text: "Hello world?", // plain text body
html: output // html body
});

console.log("Message sent: %s", info.messageId);
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));

res.render('tjetra', {layout: false});

main().catch(console.error);
});

app.listen(3000, () => console.log('Server started...'));

所以当我收到电子邮件时我正在尝试获取用户IP。我想我应该使用代码: request.connection.remoteAddress 但我不知道当用户提交表单向我发送和用户 IP 地址时如何连接。

最佳答案

您需要更准确地说明您想要做什么,但我会尽力提供帮助...如果我理解您想要在邮件正文中发送 IP,使用nodemailer

首先是如何在node.js中获取ip。请求元素有一个带有express(您使用的)的ip参数,所以只需使用:

const ip_address = req.ip;  

然后通过nodemailer发送:

let transporter = nodeMailer.createTransport({
host: 'smtp.free.fr',
port: 25,
secure: false
});
let mailOptions = {
from: '"Your subject" <no-reply@yourhost.com>',
to: 'emailReceiver@receiver.com',
subject: 'Welcome!',
text: 'Here is your text + ip: '+ ip_address,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});

还要知道,在本地主机上运行它,您的 IP 总是会返回如下:::1

关于javascript - Nodejs和Nodemailer接收用户ip地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61232283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com