2014-01-31 1 views
0

У меня есть регистрационная форма на моем веб-сайте. По завершении детали хранятся в CSV-файле, но я также хочу отправить подтверждение электронной почты пользователю. Проблема в том, что письмо приходит пустым, то, что я сделал, создается файл template.php, который содержит структуру электронной почты, которую я хочу отправить, в рамках этой структуры шаблона у меня есть функция из другого файла, который определяет дату регистрации. шаблон в template.php заворачивают в функции, которую я называю в from_to_csv.php как часть почты() atrebiutes:Письмо с подтверждением PHP

Надеемся, что это имеет смысл, и вы, ребята, понимаете меня взглянуть на код:

template.php:

<?php 

function getMailContent(){ 

$subject = "OPES Academy- Workshop confirmation"; 
$message = " 
<body style='background-color: #eeeeee; margin: 0 auto; font-family: 'lato',sans-serif'> 

<table style='background-color:#ffffff' width='600' heigth='auto' cellspacing='0' cellpadding='0' align='center'> 
    <tr> 
     <td> 
      <table width='600' style='background-color: #5e8ab5;' align='center' cellpading='0' cellspacing='0'> 
       <tr> 
        <td> 
         <p style='padding-left: 20px;'><img src='http://opesacademy.com/emails/images/logo.png' 
                  width='100' alt='Opes Academy'></p> 
        </td> 
        <td style='text-align: right; padding-right: 10px; color: #ffffff'> 
         KNOWLEDGE | WEALTH | POWER 
        </td> 
       </tr> 
      </table> 
     </td> 
    </tr> 

    <tr> 
     <td style='padding: 10px;'> 

      <h1 class='skinytxt text-center txtblue'>Thank you for reserving your place</h1> 

        <p>&nbsp;</p> 

        <p class='txt-white text-center'>Thanks for your registration, we will be looking forward to see you at the"; 

        ?> 
        <?php 
         require('helper.php'); 
         echo ConvertDate($_SESSION['date']); 
        ?> 
        <?php 
$message.=" 
        <p align='center'>Address: 6 Thomas More Square, London, E1W 1XZ</p> 

        </p> 

        <p class='txt-white text-center'>If you have any more questions we will be glad to help you, just call us on 020 3675 9000 or email us on 
         [email protected]</p> 

     </td> 
    </tr> 

</table> 

<table width='600' style='background-color: #5e8ab5;' align='center' cellpading='0' cellspacing='0'> 
    <tr> 
     <td> 
      <p style='padding-left: 10px; padding-right: 10px; font-size: 10px'>Trading and investing often 
       involves a very high degree of risk. Past results are 
       not indicative of future returns and financial instruments can go down as well as up 
       resulting 
       in you receiving less than you invested. Do not assume that any recommendations, insights, 
       charts, theories, or philosophies will ensure profitable investment. Spread betting, trading 
       binary options and CFD's carry a high risk to your capital, can be very volatile and prices 
       may 
       move rapidly against you. Only speculate with money you can afford to lose as you may lose 
       more 
       than your original deposit and be required to make further payments. Spread betting may not 
       be 
       suitable for all customers, so ensure you fully understand the risks involved and seek 
       independent advice if necessary</p> 
     </td> 
    </tr> 
</table> 

</body>"; 

$headers = "Content-type: text/html\r\n"; 

return compact($subject, $message, $headers); 
} 
?> 

form_to_csv.php:

$to = $data['email']; 

    require('template.php'); 
$mailContent = getMailContent(); 

//csv 
if(@$_POST['land']=='fw'){ 
    $path='/home/content/24/12131124/html/files/Admin/CSV_Binary/'; 
    $fName=$path.'free_workshop-'.date("F_j_Y").".csv"; 
    //mail($to, $subject, $message, $headers,"-f [email protected]"); 
    mail($to, $mailContent['subject'], $mailContent['message'], $mailContent['headers'],"-f [email protected]"); 


} 

$to переменная содержит электронное письмо, которое пользователь ввел в форму .....

+0

Он смотрит на меня, как вы повторно объявлен ПГПС 'почты)' функцию (с вашей собственной 'почты)' функции (. Разве это не должно вызывать ошибку о попытке переопределить «почту»? – crush

+0

Вы пытались распечатать вывод 'template.php' в окне браузера? –

+0

нет ошибок не высылается только по электронной почте, но пустое, но если я скопирую и пропустил код шаблона электронной почты в form_to_csv. php it works – Tomazi

ответ

2

Ваш почтовый метод не возвращает вещь. Пожалуйста, добавьте компактный («заголовки», «сообщение», «тема»);

Затем используйте возвращаемый массив в другой функции.

<?php 
// you might place the following method into mail.php 

// formerly your mail function, renamed to avoid function name clash 
// with PHP's own function mail 
function getMailContent(){ 
    $subject = "OPES Academy- Workshop confirmation"; 
    $message = "Message"; 
    $headers = "Content-type: text/html\r\n"; 

    // return the things :) 
    return compact('subject', 'message', 'headers'); 
} 

// Usage: 

// from_to_csv.php 

// you need to include the file mail.php, 
// if you want to access the function getMailContent() 
// uncomment this line, if you split the PHP code into the files. 
// include 'mail.php';  

// fetch mail content as array 
$mailContent = getMailContent(); 

// access array values 
mail($to, 
    $mailContent['subject'], $mailContent['message'], 
    $mailContent['headers'], 
    "-f [email protected]" 
); 
?> 
+0

Где я должен добавить compact() на template.php так: $ send = compact ($ header, $ message, $ subject) и в form_to_csv mail ($ to, $ send) ....? – Tomazi

+0

Я добавил небольшой пример, чтобы продемонстрировать это. –

+0

У меня есть свои последующие инструкции, пожалуйста, проверьте изменения в моем вопросе. И я получаю это сообщение об ошибке: – Tomazi

0

Локальные переменные (в данном случае $ message и $ header) не могут быть доступны за пределами локальной функции. Это называется «переменная область», и вы должны сделать еще немного чтения на нем (здесь: http://www.php.net/manual/en/language.variables.scope.php).

В этом случае сообщения $ message и $ header объявляются в функции Local Scope: function mail(), и вы пытаетесь получить к ним доступ в глобальной области при вызове функции PHP Mail.

Вы должны передать это обратно из своей функции, чтобы получить к ним доступ в файле form_to_csv.php.

0

Похоже, вы пытаетесь получить доступ к переменным $ subject, $ message и $ headers из вашей функции Mail(), они не будут доступны, если вы не вернете их сначала ... попробуйте это, в вашем шаблоне PHP говоря:

function MyMail() { 
    // Your variables and content here 


    return Array(
    "subject" => $subject, 
    "message" => $message, 
    "headers" => $headers; 
    ); 
} 

в вашем главном файле:

$to = $data['email']; 

require('template.php'); 
$content = MyMail(); 

//csv 
if(@$_POST['land']=='fw'){ 
    $path=='/home/content/CSV/'; 
    $fName=$path.'free_workshop-'.date("F_j_Y").".csv"; 
    mail($to, $content["subject"], $content["message"], $content["headers"],"-f [email protected]"); 

} 
+0

Это выглядит интересно, я попробую, но просто чтобы подтвердить $ message = точно код html-шаблона правильно ...? поэтому функция myMail() {} – Tomazi

+0

«функция myMail() {$ сообщение =„

ПРИВЕТ USER

“}» – Tomazi

+0

Да, по существу, изменить имя функции, так что не конфликтует и просто поставить обратный массив в дно –

0

супер легко исправить это было бы просто сделать template.php НЕ функцию.

удалить строку

function mail(){ 

, а затем окончание фигурной скобки

} 

и ваш скрипт будет работать нормально.

Проверить http://www.php.net/manual/en/language.variables.scope.php для получения дополнительной информации