Chinese (Simplified) (中文(简体)) translation by honeymmmm (you can also view the original English article)
既然您有一个使用平面文件系统的网站,您希望从您的用户那里获得一些反馈。 添加Disqus很容易,因为它是添加到页面的所有JavaScript代码,但它不是你想要的。 您希望他们能够直接向您发送电子邮件,以便您可以回复他们。
您可以创建一个直接从用户计算机发送电子邮件的所有JavaScript系统,但这会使您的电子邮件向垃圾邮件发送者开放,以便能够从您的代码中检索它并将其出售给其他垃圾邮件发送者。 因此,您需要在服务器上隐藏您的电子邮件地址。
本教程是关于向新的PressCMS添加电子邮件消息系统(即phpPress,rubyPress,nodePress和goPress)。 我从前端开始,然后为每个系统寻址后端。 我假设您的系统上已经有这些服务器。
如何在浏览器中创建表单
由于每个服务器的前端代码都相同,因此您必须将这些新文件复制到每个服务器目录中。 因此,我将讨论从服务器目录引用的路径中的文件。
此表单脚本不是在主题中添加特定于表单的样式,而是将所有内容集中在一个位置。 使用以下内容在网站的site/parts
目录中创建文件questions.html:
<!-- Styling for the form --> <style> form { margin: 20px auto; width: 400px; padding: 1em; border: 1px solid #f0d5ad; border-radius: 1em; } form div + div { margin-top: 1em; } label { display: inline-block; width: 90px; text-align: right; } input, textarea { width: 300px; -moz-box-sizing: border-box; } input:focus, textarea:focus { border-color: #000; } textarea { vertical-align: top; height: 5em; resize: vertical; } button { margin-top: 10px; margin-left: 8em; } </style> <!-- HTML for the Form --> <form action="/api/message" method="post"> <div> <label for="Name">Name:</label> <input id="Name" name="Name" type="text" value="" pattern="[a-zA-Z]{3,3} [a-zA-Z]{3,3}" title="First and Last name." autofocus required /> </div> <div> <label for="Email">Email:</label> <input id="Email" name="Email" type="email" pattern="[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}" title="Valid Email only." value="" required /> </div> <div> <label for="Message">Message:</label> <textarea id="Message" name="Message" type="text" value="" required></textarea> </div> <button type="submit">Send Message</button> </form>
这将创建一个基本表单,要求提供全名(名字和姓氏),电子邮件和消息。 此表单使用正则表达式来确保名称和电子邮件地址有效。 如果用户输入到这些字段中的任何内容与pattern
指令中的正则表达式不匹配,则不会提交表单。 弹出窗口将要求用户使用title
参数中的消息正确填写该字段。 每个输入字段也具有required
的原语。 这样就不会提交空白表格。 这是您应该在前端使用的最低限度的数据验证。
form
元素中的action
指令告诉Web浏览器将表单数据提交到哪个地址。 method
指令告诉浏览器以post
方式发送。 表单数据将放入对服务器的post请求的URL中。 这是一个查询字符串。 然后,服务器处理查询字符串中的信息。
在site/pages
目录中,创建文件contact.md
并放置以下代码:
### Contact Us This is a simple contact form. Please fill in your name, first and last, email address, and message. I will get back to you as soon as possible. Thanks. {{{question}}}
保存后,您可以尝试服务器中的页面。 在浏览器中,打开页面http://localhost:8081/contact。

“联系我们”页面如上图所示。 注意在加载时直接突出显示Name字段。 autofocus
指令创建了所需的行为。 拥有用户需要自动键入的第一个字段始终是一个好的设计。
发送消息后,向用户发送确认消息会很好。 在site/pages
目录中,创建文件messagesent.md
并放置此代码:
### Message was sent Thank you so much for taking time to send me a message. I will reply as soon as possible.
只是一条简单的消息,以便用户知道消息已正确发送。 您可以根据需要进行扩展。

使用goPress处理表单
为了清理用户给出的消息,我使用的是Blue Monday库。 要在系统上加载该库,您需要运行以下命令行:
go get github.com/microcosm-cc/bluemonday
这将使库可用于您的程序。 这是唯一需要的非标准库。
打开goPressServer.go
文件并将其添加到import()
语句内的文件顶部:
"fmt" "github.com/hoisie/web" "net/smtp" "github.com/microcosm-cc/bluemonday"
通过电子邮件发送来自服务器的消息需要这些库。 在具有goPress.DefaultRoutes
的行之后(函数调用,添加以下代码:
// // Setup special route for our form processing. // goPress.SetPostRoute('/api/message', postMessage)
这将设置/api/message
的post路由以运行postMessage()
函数。 在文件的末尾,添加以下代码:
// // Function: postMessage // // Description: This function will send // the message from them // the website to the owner // of the site. // // Inputs: // ctx The web server // context. // func postMessage(ctx *web.Context) string { // // Get the post information and send the // email. // name := ctx.Params["Name"] from := ctx.Params["Email"] p := bluemonday.UGCPolicy() message := p.Sanitize(ctx.Params["Message"]) to := "<your email address>" subject := "Message from User:" + name + " of CustomCT.com" sendEmail(to, from, subject, message) // // Get the messagesent page contents and // process it. // pgloc := goPress.SiteData.Sitebase + "pages/messagesent" return goPress.RenderPageContents(ctx, goPress.GetPageContents(pgloc), pgloc) } // // Function: sendEmail // // Description: This function sends an // email message. // // Inputs: // to The email address // to send the // message // from The email address // of the person // sending the // message // subject The subject of the // message // message The message of the // email // func sendEmail(to string, from string, subject string, message string) { body := fmt.Sprintf("To: %s\r\nSubject: %s\r\n\r\n%s", to, subject, message) auth := smtp.PlainAuth("", "<your email address>", "<your password>", "smtp.gmail.com") err := smtp.SendMail("smtp.gmail.com:587", auth, from, []string{to}, []byte(body)) if err != nil { // // Process the error. Currently, assuming there // isn't a problem. // } }
这两个函数构成处理从浏览器发送的电子邮件的处理程序。 /api/message
路由调用postMessage()
函数。 它检索从用户填写的表单发送的信息,使用BlueMonday库清理消息,并使用sendEmail()
函数向站点所有者发送电子邮件。 您必须在<password>
持有人中放置您的Gmail地址以代替<your email address>
持有人和密码。
在goPress.go
文件中,在SetGetRoute()
函数之后添加此函数:
// // Function: SetPostRoute // // Description: This function gives an // easy access to the // web variable setup in // this library. // // Inputs: // route Route to setup // handler Function to run that // route. // func SetPostRoute(route string, handler interface{}) { web.Post(route, handler) }
此函数与SetGetRoute()
函数完全相同。 唯一的区别是使用web.Post()
函数。
通过这些更改,您的goPress服务器现在可以从用户发送您的电子邮件。
使用nodePress处理表单
要从节点发送电子邮件,您需要首先使用以下命令行安装nodemailer library 和body-parser library :
npm install -save nodemailer npm install -save body-parser
然后,您需要加载新库并配置邮件程序对象。 在nodePress.js
文件的顶部,在加载最后一个库之后,添加以下行:
var nodemailer = require('nodemailer'); // https://nodemailer.com/ var bodyParser = require('body-parser'); // https://github.com/expressjs/body-parser // // create reusable transporter object using the // default SMTP transport // var transporter = nodemailer.createTransport('smtps://<your email name%40<your email domain>:<your password>@smtp.gmail.com');
这将加载nodemailer库并设置可重用组件以发送电子邮件。 您必须将<your email name>
替换为您的电子邮件地址的名称(即@符号前),<your email domain>
是您的电子邮件地址的域名(例如,正常Gmail的gmail.com或您的域名,如果您 将gmail设置在您的域名上)和<your password>
以及您的电子邮件帐户的密码。
在初始化nodePress变量的行之后,添加以下代码:
// // Configure the body parser library. // nodePress.use(bodyParser.urlencoded({ extended: true }));
现在,在最后一个nodePress.get()
函数调用之后,添加以下代码:
nodePress.post('/api/message', function(request, response) { // // setup e-mail data // var mailOptions = { from: request.body.Email, to: '<your email address>', subject: 'Message from ' + request.body.Name + ' on contact form.', text: request.body.Message, html: request.body.Message }; // // Send the email. // transporter.sendMail(mailOptions, function(error, info){ if(error){ return console.log(error); } // // Send the user to the message was sent okay page. // response.send(page("messagesent")); }); });
这是/api/message
地址的处理程序。 此功能获取从表单发送的信息,创建正确的电子邮件,并将其发送到<your email address>
中给出的电子邮件地址。 发送电子邮件后,它会将用户发送到/messagesent
页面。 正文解析器中间件将url参数保存到request.body
变量中并正确清理。
此代码适用于没有双因素身份验证的Gmail设置。 如果您有双因素身份验证,则可以参考Nodemailer文档进行设置。
使用rubyPress处理表单
要在Ruby中发送电子邮件,您需要使用以下命令行安装ruby-gmail库:
gem install ruby-gmail
根据您的Ruby设置,您可能需要在命令前使用sudo
。 现在加载库,将以下行添加到rubyPress.rb
文件的顶部:
require 'gmail' # https://github.com/dcparker/ruby-gmail
在所有get
定义之后,添加以下行:
post '/api/message' do # # Get the parameters from the form. # name = params[:Name] email = params[:Email] message = params[:Message] # # Create and send the email. # Gmail.new('<your email address>', '<your password>') do |gmail| gmail.deliver do to "<your email address>" from email subject "Message from " + name text_part do body message end end end # # Send the user to the message sent page. # page 'messagesent' end
通过这些添加,您的rubyPress服务器可以处理电子邮件表单。 将<your email address>
更改为您的电子邮件地址并将<your password>
更改为电子邮件服务器的密码后,脚本即告完成。
使用phpPress处理表单
最后修改的服务器是phpPress服务器。 要向服务器添加电子邮件功能,我将安装phpmailer library。 这是PHP中用于处理电子邮件的最广泛使用的库。 要安装库,您需要在phpPress目录中运行这些命令行命令:
composer update composer require phpmailer/phpmailer
不幸的是,作曲家更新将更新LightnCandy library。 这很好,因为它更快更容易使用。 但它打破了服务器代码。 在index.php文件中,找到ProcessPage()
函数并将其替换为以下代码:
// // Function: ProcessPage // // Description: This function will process // a page into the template, // process all Mustache // macros, and process all // shortcodes. // // Inputs: // $layout The layout for // the page // $page The pages main // contents // function ProcessPage( $layout, $page ) { global $site, $parts, $helpers; // // Get the page contents. // $parts['content'] = figurePage($page); // // First pass on Handlebars. // $phpStr = LightnCandy::compile($layout, $helpers); $renderer = LightnCandy::prepare($phpStr); $page = $renderer($parts); // // Process the shortcodes. // $pageShort = processShortcodes($page); // // Second pass Handlebars. // $phpStr = LightnCandy::compile($pageShort, $helpers); $renderer = LightnCandy::prepare($phpStr); $page = $renderer($parts); // // Return the results. // return($page); }
将其与旧代码进行比较,您不再需要使用临时文件。 这一切都在内存中完成,因此更快。 现在,在index.php
文件的顶部,在Jade库之后添加:
// // PHP Mailer: https://github.com/PHPMailer/PHPMailer // require 'vendor/phpmailer/phpmailer/PHPMailerAutoload.php';
这会加载phpmailer库。 现在,在最后一个$app->get()
函数之后,添加以下代码:
// // This route is for processing the post request from the // email form on the website. // $app->post('/api/message', function(Request $request, Response $response) { global $_POST; // // Get the post variables. // $Name = $_POST['Name']; $Email = $_POST['Email']; $Message = $_POST['Message']; // // Create the email message and send it. // $mail = new PHPMailer; $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = '<your email address>'; // SMTP username $mail->Password = '<your password>'; // SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $mail->setFrom($Email, $Name); $mail->addAddress('<your email>', '<your name>'); // Add a recipient $mail->Subject = "Message from $Name"; $mail->Body = $Message; if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { $newResponse = SetBasicHeader($response); $newResponse->getBody()->write(page('messagesent')); return($newResponse); } });
这是/api/message
路径的post请求处理程序。 它检索从浏览器发送的表单数据,使用它创建电子邮件,然后发送电子邮件。 PHP自动获取任何URL参数并将它们放在全局数组$ _POST
中。
您必须使用适当的电子邮件值替换<your email address>
,<your password>
和<your name>
。 如果您使用的不是Gmail SMTP服务器,则还需要更改$mail->Host
地址。
结论
我已经向您展示了如何轻松地将电子邮件表单添加到pressCMS网站。 本教程的下载包含所有这些服务器及其修改。 因此,您可以下载而不是键入。 我做了一点错误处理。 我会把剩下的作为练习留给你。
我在这里教的方法是通过URL中的数据发布表单数据。 现在,许多站点使用REST API将主体中的JSON字符串中的数据用于执行操作。 这些例程很容易被这种方法所采用,但这对你来说是一个练习(或者可能是未来的教程)。 现在您知道如何以这种方式执行此操作,将自己的表单添加到您的站点。 这种类型的定制很有趣。 你的想象力是唯一的限制。
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Update me weeklyEnvato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Translate this post