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

creating dynamic html emails with angularJS and mail with php

本文关键字:使用 创建 php html angularJS 动态 电子邮件      更新时间:2023-09-26

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

我正在尝试创建动态电子邮件内容,并通过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','$stemplateRequest','$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;

?>

电子邮件.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>

我不得不做同样的事情。但我的设置有些不同。我的后端是一个Firebase.com数据库。通过angularFire加载到我的前端,这个库用于将东西加载到一个有角度的项目中。我在前端有一个邮件模板。事实上,我计划让用户从提供的几个模板中选择他们的电子邮件模板。我只是填写字段,但就像MS Office中的邮件合并。在服务器端,我使用php-mailer(用谷歌搜索它!)用粗线条来说,这就是正在发生的事情:-创建类似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,所以需要使用基本变量。您必须在那里欺骗angular,并从一个空白DOM开始。constructMail()函数就是这样做的,它准备将数据发送到php邮件程序。

我已经在我的一个项目中成功地实现了这个体系结构。我创建了单独的服务来获取电子邮件模板。我将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并在发送电子邮件的过程中注入。