package com.reyun.util;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SendCommonPostMail {


    static String url = "http://api.sendcloud.net/apiv2/mail/send";
    static String apiUser = "service24h";
    static String apiKey = "v5WhuknT9zp4xWIz";

    public static void main(String[] args) throws IOException {
        String emial = "carrie_yz@163.com";
        String subject = "test";
        String content = "test";
        SendCommonPostMail.sendMail(emial, subject, content);

    }


    public static boolean sendMail(String toEmail, String subject, String content) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httPost = new HttpPost(url);

        List params = new ArrayList();
        // 您需要登录SendCloud创建API_USER，使用API_USER和API_KEY才可以进行邮件的发送。
        params.add(new BasicNameValuePair("apiUser", apiUser));
        params.add(new BasicNameValuePair("apiKey", apiKey));
        params.add(new BasicNameValuePair("from", "service@sendcloud.im"));
        params.add(new BasicNameValuePair("fromName", "reyun"));
        params.add(new BasicNameValuePair("to", toEmail));
        params.add(new BasicNameValuePair("subject", subject));
        params.add(new BasicNameValuePair("html", content));
        boolean success = false;
        try {
            httPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            // 请求
            HttpResponse response = httpclient.execute(httPost);
            // 处理响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
                // 读取xml文档
                String result = EntityUtils.toString(response.getEntity());
                success = true;
            } else {
                System.out.println("sendcloud response status is error.......");
            }
            httPost.releaseConnection();
        } catch (Exception e) {
            System.out.println("fail to send mail to " + toEmail);
        }
        return success;
    }
}
