使用Curl 向sendCloud发送post请求
使用sendCloud发送邮件需要我们向sendCloud提供的接口发送包括一系列信息的post请求,然后通过返回值判断是否发送成功。
代码示例
//使用的是sendCloud非模板的发送方式
function send_mail($to){
$email = $to.'@qq.com';
$ch = curl_init();
$url = 'http://sendcloud.sohu.com/webapi/mail.send.json';//此地址可以查看sendCloud文档
$timeout='5';
$str =' ';//这是邮件内容
$post_data = array(
'api_user' => ' ',//在sendCloud中设置
'api_key' => ' ',//在sendCloud中设置
'from' => ' ', // 发信人,用正确邮件地址替代
'fromname' => ' ',//发件人名字
'to' => $email,//目标邮件地址
'subject' => ' ',//邮件主题
'html' => $str,//邮件内容
);
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发送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' => ' ', # 发信人,用正确邮件地址替代
'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;
}