使用Curl 向sendCloud發(fā)送post請求
使用sendCloud發(fā)送郵件需要我們向sendCloud提供的接口發(fā)送包括一系列信息的post請求,然后通過返回值判斷是否發(fā)送成功。
代碼示例
//使用的是sendCloud非模板的發(fā)送方式
function send_mail($to){
$email = $to.'@qq.com';
$ch = curl_init();
$url = 'http://sendcloud.sohu.com/webapi/mail.send.json';//此地址可以查看sendCloud文檔
$timeout='5';
$str =' ';//這是郵件內(nèi)容
$post_data = array(
'api_user' => ' ',//在sendCloud中設(shè)置
'api_key' => ' ',//在sendCloud中設(shè)置
'from' => ' ', // 發(fā)信人渺杉,用正確郵件地址替代
'fromname' => ' ',//發(fā)件人名字
'to' => $email,//目標(biāo)郵件地址
'subject' => ' ',//郵件主題
'html' => $str,//郵件內(nèi)容
);
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, 1);
if($post_data != ''){
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, false);
$file_contents = curl_exec($ch);
$return = json_decode($file_contents);
curl_close($ch);
if(is_object($return) && $return->message=='success') {
return true;
} else {
return false;
}
}
使用file_get_contents方式向sendCloud發(fā)送post請求
這種方法比Curl簡潔
代碼示例
function send_mail($to) {
$email = $to.'@qq.com';
$url = 'http://sendcloud.sohu.com/webapi/mail.send.json';
$str =' ';
$param = array(
'api_user' => ' ',
'api_key' => ' ',
'from' => ' ', # 發(fā)信人部默,用正確郵件地址替代
'fromname' => ' ',
'to' => $email,
'subject' => ' ',
'html' => $str,
);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($param)));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$return = json_decode($result);
if(is_object($return) && $return->message=='success') {
return true;
} else {
return false;
}
}
補充代碼
function file_get_content($url) {
if (function_exists('file_get_contents')) {
$file_contents = @file_get_contents($url);
}
if ($file_contents == '') {
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}
return $file_contents;
}