Computer >> 컴퓨터 >  >> 프로그램 작성 >> Ruby

phpPress, goPress, rubyPress 및 nodePress로 양식 처리

이제 플랫 파일 시스템을 사용하는 웹 사이트가 있으므로 사용자로부터 피드백을 받고 싶습니다. Disqus를 추가하는 것은 페이지에 추가된 모든 JavaScript 코드이기 때문에 쉽지만 원하는 것이 아닙니다. 당신은 그들에게만 회신할 수 있도록 그들이 당신에게 직접 이메일을 보낼 수 있기를 원합니다.

사용자의 컴퓨터에서 직접 이메일을 보낼 수 있는 모든 자바스크립트 시스템을 만들 수 있지만 이렇게 하면 스팸 발송자가 이메일을 열어 코드에서 검색하여 다른 스팸 발송자에게 판매할 수 있습니다. 따라서 서버에서 이메일 주소를 숨겨야 합니다.

이 튜토리얼은 새 PressCMS에 이메일 메시지 시스템을 추가하는 방법에 관한 것입니다. (예: phpPress , 루비프레스 , 노드프레스 , 및 goPress ). 프론트엔드부터 시작하여 각 시스템의 백엔드에 대해 설명하겠습니다. 귀하의 시스템에 이미 이러한 서버가 있다고 가정합니다.

브라우저에서 양식을 만드는 방법

프런트 엔드 코드는 각 서버에 대해 동일하므로 이러한 새 파일을 각 서버 디렉토리에 복사해야 합니다. 따라서 서버 디렉토리에서 참조하는 경로의 파일에 대해 이야기하겠습니다.

테마에 양식별 스타일을 추가하는 대신 이 양식 스크립트에는 모든 것이 한 곳에 있습니다. questions.html 파일 만들기 site/parts 다음 콘텐츠가 포함된 웹 사이트 디렉토리:

<!-- 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가 있습니다. 원시적이기도 하다. 이렇게 하면 빈 양식이 제출되지 않습니다. 이것은 프런트 엔드에서 사용해야 하는 최소한의 데이터 유효성 검사입니다.

action form의 지시문 요소는 웹 브라우저에 양식 데이터를 제출할 주소를 알려줍니다. 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}}}

일단 저장되면 서버에서 페이지를 시험해 볼 수 있습니다. 브라우저에서 https://localhost:8081/contact 페이지를 엽니다.

phpPress, goPress, rubyPress 및 nodePress로 양식 처리 phpPress, goPress, rubyPress 및 nodePress로 양식 처리 phpPress, goPress, rubyPress 및 nodePress로 양식 처리
문의 양식 페이지

문의하기 페이지는 위의 그림과 같을 것입니다. 로드 시 이름 필드가 강조 표시됩니다. 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.

사용자가 메시지가 제대로 전송되었음을 알 수 있도록 간단한 메시지입니다. 원하는 대로 확장할 수 있습니다.

phpPress, goPress, rubyPress 및 nodePress로 양식 처리 phpPress, goPress, rubyPress 및 nodePress로 양식 처리 phpPress, goPress, rubyPress 및 nodePress로 양식 처리
메시지 전송 확인 페이지

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의 포스트 경로를 설정합니다. 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()을 사용하여 사이트 소유자에게 이메일을 보냅니다. 기능. <your email address> 대신 Gmail 주소를 입력해야 합니다. <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 라이브러리를 설치해야 합니다. 및 본문 파서 라이브러리 다음 명령줄 사용:

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로 보냅니다. 페이지. 바디 파서 미들웨어에는 request.body에 저장된 url 매개변수가 있습니다. 변수 및 적절하게 살균됩니다.

이 코드는 이중 인증 없이 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 라이브러리를 설치하겠습니다. . 이것은 이메일 작업을 위해 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 password> , 및 <your name> 이메일에 적절한 값으로 Gmail SMTP 서버가 아닌 다른 것을 사용하는 경우 $mail->Host를 변경해야 합니다. 주소도 알려주세요.

결론

pressCMS 사이트에 이메일 양식을 쉽게 추가하는 방법을 보여 드렸습니다. 이 튜토리얼의 다운로드에는 수정된 모든 서버가 있습니다. 따라서 입력하는 대신 다운로드할 수 있습니다. 약간의 오류 처리를 수행했습니다. 나머지는 연습 문제로 남겨두겠습니다.

여기서 내가 가르친 방법은 URL의 데이터와 함께 양식 데이터를 게시하는 것입니다. 오늘날 많은 사이트에서 REST API를 사용합니다. JSON의 데이터 사용 동작을 수행하기 위한 문자열. 이러한 루틴은 해당 방법론에 쉽게 채택되지만 이는 사용자를 위한 연습(또는 향후 자습서)입니다. 이제 이 방법을 알았으므로 사이트에 고유한 양식을 추가하십시오. 이러한 유형의 사용자 정의는 매우 재미있습니다. 유일한 한계는 당신의 상상력입니다.