使用phpPress,goPress,rubyPress和nodePress处理表单

现在,您已经拥有使用平面文件系统的网站,您希望从用户那里获得一些反馈。 添加Disqus很容易,因为它已将所有JavaScript代码添加到页面中,但这不是您想要的。 您希望他们能够直接给您发送电子邮件,以便您可以仅回复他们。

您可以创建一个全JavaScript系统,以直接从用户计算机发送电子邮件,但这使垃圾邮件发送者可以通过电子邮件从代码中检索该电子邮件并将其出售给其他垃圾邮件发送者。 因此,您需要在服务器上隐藏您的电子邮件地址。

本教程将向新的PressCMS (即phpPressrubyPressnodePressgoPress )添加电子邮件系统。 我先从前端开始,然后再针对每个系统解决后端。 我假设您的系统上已经有这些服务器。

如何在浏览器中创建表单

由于每个服务器的前端代码都相同,因此您必须将这些新文件复制到每个服务器目录中。 因此,我将讨论从服务器目录引用的路径中的文件。

该表单脚本没有在主题中添加特定于表单的样式,而是将所有内容都放在一个位置。 在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方法发送。 表单数据将放置在发往服务器的请求的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

联系表格页面
联系表格页面

联系我们”页面将类似于上图。 请注意,加载后直接将“名称”字段突出显示。 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处理表单

为了清理用户给出的消息,我使用了蓝色星期一库。 要在系统上加载该库,您需要运行以下命令行:

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的发布路线以运行函数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()函数将电子邮件发送给站点的所有者。 您必须将Gmail地址替换为<your email address>保留者,并将密码替换为<password>保留者。

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库body-parser库

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.com表示普通gmail或您的域名)在您的域名上设置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>给定<your email address> 。 发送电子邮件后,它将把用户发送到/messagesent页面。 主体解析器中间件将url参数保存到request.body变量中,并进行了适当的清理。

此代码适用于没有两步验证的Gmail设置。 如果您具有两重身份验证,则可以参考Nodemailer文档进行设置。

使用rubyPress处理表单

要使用Ruby发送电子邮件,您需要使用以下命令行安装ruby-gmail库:

gem install ruby-gmail

根据您的Ruby设置,您可能需要在sudo前使用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库 。 这是PHP中使用最广泛的用于处理电子邮件的库。 要安装该库,您需要在phpPress目录中运行以下命令行命令:

composer update
composer require phpmailer/phpmailer

不幸的是,作曲家更新将更新LightnCandy库 。 这很好,因为它更快,更容易使用。 但这会破坏服务器代码。 在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路径的后请求处理程序。 它检索从浏览器发送的表单数据,并使用它创建电子邮件,然后发送电子邮件。 PHP自动获取任何URL参数,并将它们放在全局数组$_POST

您将必须用<your email address>的适当值替换<your email address><your password><your name> 。 如果您使用的不是Gmail SMTP服务器,则还需要更改$mail->Host地址。

结论

我已经向您展示了如何轻松地将电子邮件表单添加到pressCMS网站。 本教程的下载内容包含所有这些服务器及其修改内容。 因此,您可以下载它而不用输入。 我已经做了一些错误处理。 我把剩下的作为练习。

我在这里教的方法是将表单数据与URL中的数据一起发布。 如今,许多网站都使用REST API ,并将数据包含在主体中的JSON字符串中,以执行操作。 这些例程很容易被该方法采用,但这是您的练习(或者可能是将来的教程)。 现在您知道如何使用此方法,将自己的表单添加到您的站点。 这种类型的自定义很有趣。 你的想象力是唯一的限制。

翻译自: https://code.tutsplus.com/tutorials/processing-forms-with-phppress-gopress-rubypress-and-nodepress--cms-27473

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值