对于我的网站,我正在尝试向用户发送电子邮件。我使用 sendgrid 提供程序通过nodeJS发送邮件。我是nodeJS的新手,我已经按照他们在页面上的说明通过命令提示符发送了邮件。但我不知道如何在真实服务器上实现它。要通过 sendgrid 发送电子邮件,我安装了他们的软件包。我想发送一封电子邮件给特定的活动。
function goMail()
{
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(MY_API_KEY);
const msg = {
to: '********1234@gmail.com',
from: '12345***@gmail.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<div class="container">
<h2>Vertical (basic) form</h2>
<form>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" onclick="goMail();">Submit</button>
</form>
</div>
</body>
</html>
请说明如何在真实服务器上运行。
答案 0 :(得分:0)
您不能直接在HTML中包含index.js文件并调用Nodejs函数。相反,您应该在Nodejs上使用Express框架并使用jQuery发布表单数据。请按照以下链接中提供的说明操作: https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
希望这个答案能指出正确的方向并解决您的问题。
答案 1 :(得分:0)
如果您已实施服务器代码,则只需在app.js文件中添加以下路由,即可创建用于向用户发送电子邮件的API
app.get('/sendEmail', (req, res) => {
let sendgrid = require('sendgrid');
let SG = sendgrid('your sendgridKey');
let request = SG.emptyRequest();
request.method = 'POST';
request.path = '/v3/mail/send';
request.body = (new sendgrid.mail.Mail(
new sendgrid.mail.Email(req.body.from),
req.body.subject, // subject
new sendgrid.mail.Email(req.body.to),
new sendgrid.mail.Content('text/html', 'your html')
)).toJSON();
SG.API(request, (err, response)=> {
if (response.statusCode >= 200 && response.statusCode < 300) {
res.send(response);
});
});
或者您可以在路由器之外定义此功能,以便您可以在任何路由中将此功能称为中间件。