使用angularJS创建动态html电子邮件并使用php创建邮件

时间:2016-07-26 03:25:22

标签: javascript html angularjs email

我一直试图解决这个问题并一直在寻找。如果这听起来很愚蠢,或者我错过了一个重复的问题,请提前道歉。

我正在尝试创建动态电子邮件内容并通过php邮件发送电子邮件。我想使用angularJS来编译html内容并使用$ http.post方法发送到submit.php来发送电子邮件。

我可以手动输入php中的html内容并没有问题但是编译动态html是个问题。

我真的不太确定如何解决这个问题,所以任何帮助都会非常感激。

谢谢,

我的角度控制器:

    $scope.url = 'submit.php';

    $scope.formsubmit = function(isValid) {


        if (isValid) {


            $http.post($scope.url, {"name": $scope.name, "email": $scope.email, "message": $scope.message }).
                    success(function(data, status) {
                        console.log(data);
                        $scope.status = status;
                        $scope.data = data;
                            $scope.result = data; 
})
}
}

submit.php

    $post_date = file_get_contents("php://input");
$data = json_decode($post_date);
$to = $data->email;
$from = "John@example.com";
$name = $data->name;
$subject = "Email from AngularJS";

$htmlContent = $data->message;

我在下面添加了我的代码:

的index.html:

    <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Dynamic Email AngularJS</title>

</head>

<body ng-app="myApp" ng-cloak>

    <div ng-controller="formCtrl">


    <pre ng-model="result">
                {{result}}
    </pre>
    <form name="userForm">
    <input type="text" class="form-control" ng-model="$parent.name" placeholder="Name Lastname" required>
    <input type="text" class="form-control" ng-model="$parent.email" placeholder="me@email.com" required>


    <div ng-view></div>
    <button ng-click="add()">New Item</button>
    <button type="submit" class="btn" ng-click="formsubmit(userForm.$valid)"  ng-disabled="userForm.$invalid">Submit </button>
    </form>
    </div>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>

    <script src="//code.angularjs.org/1.4.3/angular-route.min.js"></script>
    <script src="app.js"></script>


</body>

</html>

app.js:

myApp.controller(“formCtrl”,['$ scope','$ http','$ templateRequest','$ compile',function($ scope,$ http,$ templateRequest,$ compile){

$scope.lists = [
{
"year":"year I",
"semesters":[
                {

                "label": "Semester I",
                "max": "4",
                "courses": [
                    {"name": "Introductory Accounting I", "type": "populated"},
                    {"name": "Principles of Economics I", "type": "populated"},
                ]
                },

                {
                "label": "Semester II",
                "max": "4",
                "courses": [
                    {"name": "Accounting Method II", "type": "populated"},

                ]
                }
        ]
},

{
"year":"year II",
"semesters":[
                {
                "label": "Semester I",
                "max": "4",
                "courses": [
                    {"name": "Introductory Accounting I", "type": "levelII"},
                    {"name": "Business Finance I", "type": "levelII"}
                ]
                },

                {
                "label": "Semester II",
                "max": "4",
                "courses": [
                    {"name": "Accounting Method II", "type": "levelII"},
                    {"name": "Management Accounting II", "type": "levelII"},

                ]
                }
        ]
}
]

$scope.add = function () {
  $scope.lists.push(
      {
"year":"year III",
"semesters":[
                {
                "label": "Semester I",
                "max": "4",
                "courses": [
                    {"name": "Introductory Accounting I", "type": "levelII"},
                    {"name": "Business Finance I", "type": "levelII"}
                ]
                },

                {
                "label": "Semester II",
                "max": "4",
                "courses": [
                    {"name": "Accounting Method II", "type": "levelII"},
                    {"name": "Management Accounting II", "type": "levelII"},

                ]
                }
        ]
});
}

$scope.url = 'submit.php';

$scope.formsubmit = function(isValid) {

    if (isValid) {

        $templateRequest('email.html').then(function(html) {

        $scope.contentHtml = $compile(html);
        });
        $http.post($scope.url, {"name": $scope.name, "email": $scope.email, "message": $scope.contentHtml }).
                success(function(data, status) {
                    console.log(data);
                    $scope.status = status;
                    $scope.data = data;
                    $scope.result = data; 
                })
    }else{

          alert('Form is not valid');
    }
}

}]);

submit.php:

    <?php


$post_date = file_get_contents("php://input");
$data = json_decode($post_date);
$to = $data->email;
$from = "Sam@example.com";
$name = $data->name;
$subject = "Dynamic Email";


$htmlContent = $data->message;

// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// Additional headers
$headers .= 'From: '.$from . "\r\n";


if(mail($to,$subject,$htmlContent,$headers)) {

    echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";    

} else {


    echo 'Sorry there was an error sending your message. Please try again later.';

}


echo "Name : ".$data->name."\n";
echo "Email : ".$data->email."\n";
echo "Hero : ".$data->hero."\n";
echo "Message": $htmlContent;



?>

email.html

<table ng-repeat="list in lists">
    <tr>
        <td>
            <h1>{{list.year}}</h1>
        </td>
    </tr>
    <tr>
        <td ng-repeat="semester in list.semesters">
            <table>
                <tr>
                    <td>
                        <h3>{{semester.label}}</h3>


                         <ul>
                             <li ng-repeat="course in semester.courses">{{course.name}}</li>
                         </ul>

                    </td>
                </tr>
            </table>
        </td>

    </tr>
</table>

2 个答案:

答案 0 :(得分:0)

我必须做同样的事情。但我的设置有些不同。我的后端是一个Firebase.com数据库。通过angularFire加载到我的前端,angularFire是用于将内容加载到角度项目中的库。我在前端有一个邮件模板。事实上,我计划让用户从几个提供的电子邮件模板中选择他们的电子邮件模板。我只是填写字段,但像MS-Office中的邮件合并。 在服务器端,我使用php-mailer(google it!) 在大行中,这就是发生的事情: - 创建像mailTo这样的vars(我必须发送邮件的所有电子邮件)并将它们绑定到$ scope(是的,我知道我不应该这样做,但留在我身边) - 来自应该在邮件中的数据库记录的其他stuf,我再次绑定到$ scope。 - 然后我这样做:

$templateRequest("templates/mail-packs/mail-1.html")
       .then(function(emailtemplate) {
             var base = angular.element('<div></div>');
             base.html(emailtemplate);
             $compile(base)($scope);
             $timeout(function(){
                  mail = base.html()
                  console.log(mail);
                  constructMail(mail)
             }, 300)
        })

需要基础变量,因为你没有遵守DOM。你必须在那里欺骗角度并从空白DOM开始。 函数constructMail()是一个正在执行此操作的函数,准备将数据发送到php-mailer。

答案 1 :(得分:0)

我已经在一个项目中成功实现了这种架构。我创建了单独的服务来获取电子邮件模板。我将URL和$ scope对象传递给getTemplate()方法,该方法将向我返回已编译的电子邮件模板。

templateService.js

angular.module('myApp').factory("TemplateService", ['$resource', '$q', '$rootScope', '$templateRequest', '$compile', '$timeout', function ($resource, $q, $rootScope, $templateRequest, $compile, $timeout) {
    class TemplateService {
        constructor() {

        }

        /**
         * Get the template from url and then compile it with data.
         * @param url
         * @param $scope
         * @returns {*|Promise<T>}
         */
        static getTemplate(url, $scope) {
            return $templateRequest(url)
                .then(function(response){
                    let template = angular.element('<div></div>');
                    template.html(response);

                    //3. Pass the data to email template, in data will be merged in it
                    $compile(template)($scope);

                    return $timeout(function(){
                        return template.html();
                    }, 300);
                })
                .catch(function(err){
                    return $templateRequest('views/templates/404.html');
                });
        }
    }

    return TemplateService;
}]);

contact_email.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Email</title>
    </head>
<body leftmargin="0" marginwidth="0" topmargin="0" marginheight="0" offset="0">
<table align="center" border="0" cellpadding="0" cellspacing="0" height="100%" width="100%" id="bodyTable" style="background: #f2f2f2;padding:40px 10px;">
    <tr>
        <td align="center" valign="top" id="bodyCell">
            <table border="0" cellpadding="0" cellspacing="0" id="templateContainer" style="background: white;text-align: center;border: 1px solid grey;padding: 20px;box-shadow: 0 0 5px 2px grey;margin:0 auto;">
            <tr>
                <td align="center" valign="top">
                    <table border="0" cellpadding="0" cellspacing="0" width="100%" id="templateBody">
                        <tr>
                            <td valign="top" class="bodyContent">
                                Hello  {{ contactEmailCtrl.contact.firstName }} 
                                <p compile="contactEmailCtrl.message">
                                </p>
                                <p>
                               
                                </p>
                            </td>
                        </tr>
                    </table>
                </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
</body>
</html>

控制器中的用法 contact.controller.js

angular.module('myApp').controller('ContactController', ['$scope', 'Global', 'TemplateService', $scope, Global, TemplateService]) {
let vm = this;
vm.sendEmail = function(params) {
        
        //1. Prepare email template, Pass data to email template and compile it
        $scope.contactEmailCtrl = {
            user: Global.user,
            message: $scope.emailCommunication.message || null,
        };

        TemplateService.getTemplate('views/templates/emails/contact_email.html', $scope).then(function(emailBody) {               
            console.log('--> | emailBody ', emailBody);
            //Todo: Send email
            let emailParams = {
              tos: 'example@example.com',
              subject: 'subject goes here',
              emailBody: emailBody
            }
            // EmailService.sentEmail(emailParams); // Either send by PHP or Nodejs Or Ruby whatever
         

        }).catch(function(err) {
            console.log(' err ', err);
        });
    };
    
    }

这是整个实现。希望这对希望维护干净架构并分离电子邮件html并即时注入以发送电子邮件的人有所帮助。