【问题标题】:creating dynamic html emails with angularJS and mail with php使用 angularJS 创建动态 html 电子邮件和使用 php 创建邮件
【发布时间】:2016-11-29 13:11:51
【问题描述】:

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

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

提交.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');
    }
}

}]);

提交.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>

【问题讨论】:

    标签: javascript html angularjs email


    【解决方案1】:

    我已经在我的一个项目中成功实现了这个架构。我创建了单独的服务来获取电子邮件模板。我将 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>

    在控制器中的使用 联系人.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 并即时注入以发送电子邮件。

    【讨论】:

    • 我参考了这个link
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-02-14
      • 2013-07-26
      • 2023-03-14
      • 1970-01-01
      • 2017-09-26
      • 2019-01-04
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      相关资源
      最近更新 更多