2012-04-05 2 views
1

아래 코드를 사용하여 Sendgrid WebAPI를 SMTP 또는 Swiftmailer없이 사용하고 싶습니다. 긴 문자열 변수를 생성하지 않고 모든 인용 부호를 이스케이프 처리하고 각 변수를 반향하지 않고 전체 동적 웹 페이지를 'html'$ params 배열로 전달할 수 있습니까? 각 이메일은 크게 달라 지므로 Sendgrid의 템플릿/메일 병합 옵션이 작동하지 않습니다. 감사!Sendgrid Web API로 동적 PHP HTML 보내기

다음은 간단한 HTML 예제 (광산이 훨씬 더 동적 콘텐츠) :

<html> 
    <head></head> 
    <body> 
    <p>Hi I'm <?php echo $name; ?>!<br> 
     <span style="color: #999999; font-size: 11px;">How are you?</span><br> 
    </p> 
    </body> 
</html> 

$url = 'http://sendgrid.com/'; 
$user = 'USERNAME'; 
$pass = 'PASSWORD'; 

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


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

// 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); 
+0

SMTP 사용시 문제가 있습니까? – Borealid

+0

아무 문제가 없습니다 ... 웹 API를 사용하면 추가 라이브러리가 필요 없으므로 간단합니다. – Jeff

답변

1

당신이 Smarty 같은 템플릿 엔진을 사용하는 것입니다 필요한 HTML을 생성하는 가장 좋은 방법. 그래서 예에서, 실제로 이메일을 보내는 곳 이상, 당신은 같은 것을 할 것 :

include('Smarty.class.php'); 

$smarty = new Smarty; 
$smarty->assign('name', 'Swift'); 
$smarty->assign('name', 'SendGrid'); 
$smarty->assign('address', '123 Broadway'); 

// Store it in a variable 
$emailBody = $smarty->fetch('some_dynamic_template.tpl'); 

그리고를 당신은 실제로 새로운 동적 HTML 본문으로 이메일을 보낼 필요가있을 때 :

.... 

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

.... 
+0

감사합니다. 마이크. 나는 전에 Smarty를 사용한 적이 없다. 두 번째 PHP 파일을 만들고 file_get_contents()를 사용하여 $ emailBody 변수로 가져 오는 방법으로 비슷한 작업을 수행 할 수 있습니까? – Jeff

+0

Jeff, 역동적 인 내용을 대체해야하기 때문에 그보다 조금 까다 롭습니다. 그러나 다음은'file_get_contents'를 사용하여 간단한 템플릿 시스템을 만드는 방법에 관한 훌륭한 기사입니다. http://www.broculos.net/en/article/how-make-simple-html-template-engine-php – Swift