我一直在尝试设置一个简单的表单,在提交时会向用户发送电子邮件。我一直在使用nodejs并安装了nodemailer来帮助我。我正在使用Gmail作为SMTP服务器,并遇到了一些问题。这是html:
<title> Schedule an Appointment - Name </title>
<link rel="stylesheet" type="text/css" href="public/styles.css">
<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="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="public/script.js"></script>
<ul id="nav">
<li><a href="page.html"> Home </a><br>
<br>
<li><a class="active" href=""> Appointment </a> <br>
<br>
<li><a href="specsPage.html"> Build </a> <br>
<br>
<li><a href="contactPage.html"> Contact </a> <br>
<br>
</ul>
<div id="schedulePage">
<h4> Schedule an Appointment </h4>
<div id="fullForm">
First Name: <input id="firstname" type="text" name="firstname" placeholder="First Name..."> <br>
<br>
Last Name: <input id="lastname" type="text" name="lastname" placeholder="Last Name..."> <br>
<br>
Email: <input id="email" type="text" name="email" placeholder="Email..."> <br>
<br>
Phone Number: <input id="phone" type="text" name="phone" placeholder="Callback Number..."> <br>
<br>
<input id="send_email" type="submit" name="submit" value="Submit">
<span id="message"></span>
</div>
</div>
脚本:
$(document).ready(function(){
var from,to,subject,text;
$("#send_email").click(function(){
to=$("#email").val();
firstname=$("#firstname").val();
lastname=$("#lastname").val();
$("#message").text("Sending E-mail...Please wait");
$.get("http://localhost:4000/send",{to:to,subject:firstname,text:lastname},function(data){
if(data=="sent"){
$("#message").empty().html(" Email is been sent at " + to + " . Please check inbox !");
}
});
});
答案 0 :(得分:0)
首先,您需要在Gmail中启用安全性较低的应用 How to enable less secure apps in google
然后安装node-mailer
npm i nodemailer
将此功能粘贴到您的代码中
var nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport('smtps://yourmail%40gmail.com:yourpass@smtp.gmail.com');
// setup e-mail data with unicode symbols
function sendmail(to,subject,text,html,info) {
var mailOptions = {
from: '"Testing Mail" <youmail@gmail.com>', // sender address
to: to, // list of receivers
subject: subject, // Subject line
text: text, // plaintext body
html: html // html body
};
transporter.sendMail(mailOptions, function(error, infoo){
var res={
responsecode:''
}
if(error){
res.responsecode=401;
return info(new Error(res.responsecode),null);
}
res.responsecode=200;
info(null,res.responsecode+infoo.response);
});}
现在调用函数
app.get('/send',function (req,res) {
//pass value from your html form here
sendmail('to', 'subject', 'body', '<h1>its Html</h1>', function (err, info) {
if (err) {
console.log("Error is " + err)
return
}
console.log("Email sent. " + info)
})})