2015-01-02 3 views
6

В настоящее время у меня возникла проблема с попыткой использовать Azure в качестве SMTP-сервера. Я пытаюсь создать простую форму контакта, которая отправит электронное письмо, когда вы нажмете отправить. PHP-код прост и работает на другом сервере, как и в предыдущем проекте, но теперь мне нужно использовать сервер Microsoft Azure и из того, что я прочитал, мне нужно использовать либо вызов cURL, либо вызов sendmail API. Кто-нибудь знает, как это сделать, поскольку я не могу заставить его работать. Это код, который Microsoft говорят, что нужно использовать, чтобы получить CURL для работы,php call with cURL в windows azure

// Generate curl request 
$session = curl_init($request); 

// Tell curl to use HTTP POST 
curl_setopt ($session, CURLOPT_POST, true); 

// Tell curl that this is the body of the POST 
curl_setopt ($session, CURLOPT_POSTFIELDS, $params); 

// Tell curl not to return headers, but do return the response 
curl_setopt($session, CURLOPT_HEADER, false); 
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); 

// obtain response 
$response = curl_exec($session); 
curl_close($session); 

// print everything out 
print_r($response); 

Я полагаю, что это намного проще, чем я могу видеть, но где именно я кладу PHP код в этом Curl код, чтобы получить это работать? Есть ли что-то еще, что мне не хватает на лазурной стороне вещей? У меня уже установлен sendmail на моем аккаунте, который был всем, что они сказали мне нужно.

вот мой PHP код в любом случае, если это помогает

$url = 'https://api.sendgrid.com/'; 
$user = '[email protected]'; 
$pass = 'password7'; 

$params = array(
     'api_user' => $user, 
     'api_key' => $pass, 
     'to' => '[email protected]', 
     'subject' => 'testing from curl', 
     'html' => 'testing body1', 
     'text' => 'testing body2', 
     'from' => '[email protected]', 
    ); 

$request = $url.'api/mail.send.json'; 

if ($_POST["submit"]) { 
     $name = $_POST['name']; 
     $email = $_POST['email']; 
     $message = $_POST['message']; 
     $human = intval($_POST['human']); 
     $from = 'Contact Form'; 
     $to = '[email protected]'; 
     $subject = 'Message from Contact Form '; 

     $body = "From: $name\n E-Mail: $email\n Message:\n $message"; 

     // Check if name has been entered 
     if (!$_POST['name']) { 
      $errName = 'Please enter your name'; 
     } 

     // Check if email has been entered and is valid 
     if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { 
      $errEmail = 'Please enter a valid email address'; 
     } 

     //Check if message has been entered 
     if (!$_POST['message']) { 
      $errMessage = 'Please enter your message'; 
     } 
     //Check if simple anti-bot test is correct 
     if ($human !== 5) { 
      $errHuman = 'Your anti-spam is incorrect'; 
     } 

// If there are no errors, send the email 
if (!$errName || !$errEmail || !$errMessage || !$errHuman) { 
    if (mail ($to, $subject, $body, $from)) { 
     $result='<div class="alert alert-success">Thank You! I will be in touch</div>'; 
    } else { 
     $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>'; 
    } 
} 
    } 
+1

Добавьте это после того, как ваш 'curl_exec', чтобы получить дополнительную информацию об отладке:' если (curl_errno ($ сессия)) {эхо 'Curl ошибка:'. curl_error ($ сессия); } '. Добавьте это к своему вопросу и давайте посмотрим, можно ли решить эту проблему. С http://php.net/manual/en/function.curl-errno.php – Tom

+0

Спасибо за помощь. Том, мне действительно удалось заставить его работать только в начале недели. Положите ответ на сообщение там, чтобы объяснить мои работы (и ошибки), чтобы оценить ваши усилия, чтобы помочь :) –

ответ

5

Кто хочет увидеть некоторые плохие методы кодирования ??? Итак, после многократного вытягивания волос и исследований я выяснил, как заставить мою PHP-форму работать. Я отредактирую код с помощью самих объясняющих переменных, поэтому прочитайте код и, надеюсь, ему станет понятно, почему все происходит в определенных местах. Помните, что это полезно, только если у вас есть сервер azure для Windows, и вам почему-то нужна PHP-форма для работы на сервере. Вам необходимо установить sendmail на свой портал Windows, затем выполните шаги, чтобы получить URL-адрес, пароль и имя пользователя. все это входит в ваш php-файл. (Ну, мои работы, но не Theres несколько избыточных битов кода там, ничего опасного только я говорю, что я сдаюсь, это работает, я буду переделывать его на более поздний срок)

$url = 'https://api.sendgrid.com/'; 
$user = 'this is provided user attribute'; 
$pass = 'password1'; 

$params = array(
     'api_user' => $user, 
     'api_key' => $pass, 
     'to' => '[email protected]', 
     'subject' => 'subject of the email', 
     'html' => 'I am the HTML parameter', 
     'text' => 'I am the text parameter', 
     'from' => $email, 
    ); 

$request = $url.'api/mail.send.json'; 

if ($_POST["submit"]) { 
     $name = $_POST['name']; 
     $email = $_POST['email']; 
     $message = $_POST['message']; 
     $human = intval($_POST['human']); 
     $from = "From: Contact Form"; 
     $mobile = $_POST['number']; 

     $to = '[email protected]'; 
     $subject = 'Message for subject line of email'; 

     $humanBool=66; 

     $body = "From: $name\n E-Mail: $email\n Message:\n $message"; 

     // now we go through some validation of the parts in the form 
     // to check everything was entered. In hindsight HTML 5 
     // 'required' attribute is much easier and fulfills exactly 
     // what I did here anyway. 
     // Check if name has been entered 
     if (!$_POST['name']) { 
      $errName = 'Please enter your name'; 
     } 

     // Check if email has been entered and is valid 
     if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { 
      $errEmail = 'Please enter a valid email address'; 
     } 

     //Check if message has been entered 
     if (!$_POST['message']) { 
      $errMessage = 'Please enter your message'; 
     } 
     //Check if simple anti-bot test is correct 
     if ($human !== 5) { 
      $errHuman = 'Your anti-spam is incorrect'; 
     }else{ 
      $humanBool = 66; 
     } 

     // If there are no errors in the data fields i.e. missing data 
     if (!$errName && !$errEmail && !$errMessage && !$errHuman) { 
      //and the human anti spam field is correct. 
      if($humanBool == 66){ 
       //do the email sending magic. 
       //create url for api call 
       // ready for that repetitive code? 
       $url = 'https://api.sendgrid.com/'; 
       //create array params for api call 
       //these params are what appear in the email that arrives into your email account. 
       $params = array(
        'api_user' => $user, 
        'api_key' => $pass, 
        'to'  => '[email protected]', 
        'subject' => 'Subject', 
        'html'  => "From: $name\n\r Message:\r\n $message", 
        'text'  => 'this is the text element', 
        'from'  => $email, 
       ); 

       // I don't why I concatenated this but one of the 
       // resources I used while researching said to do it. It 
       // worked, it's also unneccessary. $request is just 
       // https://api.sendgrid.com/api/mail.send.json. I think 
       // the founder of that article is just having a private 
       // joke at people using his code for help. 

       //concatenate api url to url above 
       $request = $url.'api/mail.send.json'; 

       //debugging 
       //$error = error_get_last(); 
       //echo this to see what errors are happening in the file 

       // Repetitive code..... 
       $url2 = 'https://api.sendgrid.com/api/mail.send.json'; 


       // Okay queue magic time. I'll explain it as overview 
       // here and you guys can step through after the 
       // explanation. 1) magic. 2) Sorcery. I don't quite get 
       // all of it so my explanation would be poor but I 
       // will say HOW it works overall. All previous arrays 
       // and variables are packaged up in one pack and then 
       // a service is called and they are sent as $result 



       // use key 'http' even if you send the request to https:// 
       $options = array(
        'http' => array(
         'header' => "Content-type: application/x-www-form-urlencoded\r\n", 
         'method' => 'POST', 
         'content' => http_build_query($params), 
        ), 
       ); 
       $context = stream_context_create($options); 
       $result = file_get_contents($url2, false, $context); 

       // debugging code if something goes wrong 
       // var_dump($result); 
       $result='<div class="alert alert-success">Thank You! I will be in touch</div>'; 

       // this is here to reset the page and clear the fields 
       // of the form once mail has been sent. 
       $page = $_SERVER['PHP_SELF']; 
       $sec = "3"; 
       header("Refresh: $sec; url=$page"); 

      }else{ 
        $result='<div class="alert alert-danger">Human checked failed</div>'; 
      } 


      }else{ 
       $result='<div class="alert alert-danger">Validation error</div>'; 
      } 
} 


?> 
// after this goes the HTML form here is one box from the form as its 
// all the same no need to repeat it all I think. 

<div class="form-group"> 

         <div class="col-xs-10 col-xs-offset-1"> 
          <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" style="text-transform:capitalize" value="<?php echo htmlspecialchars($_POST['name']); ?>" required> 
          <?php echo "<p class='text-danger'>$errName</p>";?> 
         </div> 

Теперь, когда у меня есть это разработанные, пожалуйста, не стесняйтесь брать мой код для собственных нужд, если вам нужно. Я настоятельно рекомендую вам не использовать windows azure для такого рода вещей и просто получить другой сервер, на котором работает функция php 'mail', что намного проще, я также обнаружил другие проблемы с окнами azure, которые можно сделать с iFrames, останавливающим адаптивные макеты дизайна (проверьте источник страницы, если это произойдет, и посмотрите, есть ли ссылка в источнике вашей страницы, следуйте по ссылке и посмотрите, разрешает ли она вашу отзывчивую проблему). И как всегда, если у кого-то есть какие-либо вопросы по поводу кода выше, пожалуйста, напишите мне. Обычно я возвращаюсь к вам в течение дня.

Dex

+2

Привет. Там, через 2 дня, я нашел ваше сообщение! Просто немного изменил ваш код сейчас - и, наконец, решил великую загадку Azure PHP. Моя жизнь была безжалостной. Большое спасибо! – ForeverLearning

+2

Большое вам спасибо! –