MailSendDemo


概览

  • 支持.Net版本:2.0以上
  • 依赖三方库 Newtonsoft.Json.dll


代码示列

using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Security.Cryptography;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SUBMAILDEMO
{
    public class MailSendDemo
    {
        private const string API_MailSend = "https://api.mysubmail.com/mail/send.json";
        private const string API_Timestamp = "https://api.mysubmail.com/service/timestamp.json";
        public void Send()
        {
            string appid = "16xxx";
            string appkey = "5d5d513xxxxxc6f57eb7e4c7a5a6";
            string sign_version = "2";
            string sign_type = "md5";
            string to = "";
            string from = "";
            string from_name = "";
            string reply = "";
            string cc = "";
            string bcc = "";
            string subject = "";
            string text = "";
            string html = "";

            JObject vars = new JObject();
            vars.Add("param1", "张三丰");
            vars.Add("param2", "张无忌");

            JObject links = new JObject();
            links.Add("link1", "xxxx");
            links.Add("link2", "xxxx");

            //附件。最多支持9个附件
            Atta atta = new Atta();
            atta.add("text2.jpg", "/Users/submail/Desktop/text2.jpg");
            atta.add("text3.jpg", "/Users/submail/Desktop/text3.jpg");

            string headers = "";
            string asynchronous = "true";
            string tag = "xxxx";

            Dictionary<string, string> d = new Dictionary<string, string>();
            d.Add("appid", appid);
            d.Add("to", to);
            d.Add("from", from);
            d.Add("from_name", from_name);
            d.Add("reply", reply);
            d.Add("subject", subject);
            d.Add("asynchronous", asynchronous);
            d.Add("tag", tag);
            //如果不使用加密方式或者signature传normal则signature参数传入appkey的值
            if (sign_type.Equals("md5") || sign_type.Equals("sha1"))
            {
                string timestamp = JObject.Parse(HttpGet(API_Timestamp))["timestamp"].ToString();
                d.Add("sign_type", sign_type);
                d.Add("timestamp", timestamp);
                d.Add("sign_version", sign_version);
                if (sign_type.Equals("md5"))
                {

                    d.Add("signature", GetMD5Signature(FormatRequest(d), appid, appkey));
                }
                else
                {
                    d.Add("signature", GetSHA1Signature(FormatRequest(d), appid, appkey));
                }
            }
            else
            {
                d.Add("signature", appkey);
            }
            d.Add("cc", cc);
            d.Add("bcc", bcc);
            d.Add("text", text);
            d.Add("html", html);
            d.Add("vars", vars.ToString());
            d.Add("links", links.ToString());
            d.Add("atta", atta.toJsonString());
            d.Add("headers", headers);
            string response = Httppost(API_MailSend, d);
            Console.WriteLine(response);

        }


        //http post请求
        public string Httppost(string url, Dictionary<string, string> parameters)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求对象
            request.Method = "POST";//请求方式
            request.ContentType = "application/x-www-form-urlencoded";//链接类型
                                                                      //构造查询字符串
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                bool first = true;
                foreach (string key in parameters.Keys)
                {

                    if (!first)
                    {
                        buffer.AppendFormat("&{0}={1}", HttpUtility.UrlEncode(key, Encoding.UTF8), HttpUtility.UrlEncode((string)parameters[key], Encoding.UTF8));
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", HttpUtility.UrlEncode(key, Encoding.UTF8), HttpUtility.UrlEncode((string)parameters[key], Encoding.UTF8));
                        first = false;
                    }
                }
                Console.WriteLine("requestParam:" + buffer.ToString());
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                //写入请求流
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                    stream.Close();
                }
            }
            HttpWebResponse hwp = request.GetResponse() as HttpWebResponse;
            string response = GetResponseString(hwp);
            hwp.Close();
            return response;
        }


        //获取服务器时间戳
        public string HttpGet(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;//创建请求对象
            request.Method = "GET";//请求方式 
            request.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse hwp = request.GetResponse() as HttpWebResponse;
            string response = GetResponseString(hwp);
            hwp.Close();
            return response;
        }

        public string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }


        //加密参数升序
        public string FormatRequest(Dictionary<string, string> data)
        {
            StringBuilder builder = new StringBuilder();
            if (data.Count > 0)
            {
                List<KeyValuePair<string, string>> lst = new List<KeyValuePair<string, string>>(data);
                lst.Sort(delegate (KeyValuePair<string, string> s1, KeyValuePair<string, string> s2)
                    {
                        return s1.Key.CompareTo(s2.Key);
                    });
                foreach (KeyValuePair<string, string> kvp in lst)
                {
                    if (kvp.Value != null)
                    {
                        builder.Append(string.Format("{0}={1}&", kvp.Key, kvp.Value));

                    }
                }
            }
            string formatData = builder.ToString();
            Console.WriteLine(formatData);
            if (formatData.Length > 0)
            {
                return formatData.Substring(0, formatData.Length - 1);
            }
            return null;
        }

        //获取md5加密后的签名字符串
        private string GetMD5Signature(string data, string appid, string appkey)
        {
            string signStr = string.Format("{0}{1}{2}{3}{4}", appid, appkey, data, appid, appkey);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = Encoding.GetEncoding("utf-8").GetBytes(signStr);
            byte[] targetData = md5.ComputeHash(fromData);
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < targetData.Length; i++)
            {
                sBuilder.Append(targetData[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }

        //获取sha1加密后的签名字符串
        private string GetSHA1Signature(string data, string appid, string appkey)
        {
            string signStr = string.Format("{0}{1}{2}{3}{4}", appid, appkey, data, appid, appkey);
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] fromData = Encoding.GetEncoding("utf-8").GetBytes(signStr);
            byte[] targetData = sha1.ComputeHash(fromData);
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < targetData.Length; i++)
            {
                sBuilder.Append(targetData[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
    }

    class Atta
    {
        private JArray jarray = new JArray();

        public void add(String name, String path)
        {

            JObject jobject = new JObject();
            jobject.Add("name", name);
            jobject.Add("data", FileToBase64(path));
            jarray.Add(jobject);
        }

        public String toJsonString()
        {
            return jarray.ToString();
        }

        public string FileToBase64(string filePath)
        {
            string strRet = "";
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open);
                byte[] bt = new byte[fs.Length];
                fs.Read(bt, 0, bt.Length);
                strRet = Convert.ToBase64String(bt);
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                strRet = null;
            }
            return strRet;
        }
    }

}