【发布时间】:2015-06-07 02:29:02
【问题描述】:
我目前正在使用 Mailgun 通过他们的 REST API 服务在我的应用程序中执行一些电子邮件发送。他们的示例使用了 RestSharp,它已经在我的项目中获得了 MS Web API 休息客户端,我不愿意为此功能安装另一个。标准电子邮件使用 HttpClient 可以正常工作,但是在添加附件时我有点不知所措。
发送带有附件的电子邮件的代码如下...
RestClient client = new RestClient();
client.BaseUrl = new Uri("https://api.mailgun.net/v3");
client.Authenticator = new HttpBasicAuthenticator("api", "MailgunKeyGoesHere");
RestRequest request = new RestRequest();
request.AddParameter("domain",
"mailgundomain.mailgun.org", ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
request.AddParameter("from", "Mailgun Sandbox <postmaster@mailgundomain.mailgun.org>");
request.AddParameter("to", "My Email <myemail@testdomain.co.uk>");
request.AddParameter("subject", "Hello");
request.AddParameter("text", "This is the test content");
request.AddFile("attachment", Path.Combine("C:\\temp", "test.jpg"));
request.Method = Method.POST;
client.Execute(request);
当我在 Linqpad 中测试它时,这很好用。但是,我的代码不是,我似乎看不到该怎么做。
var client = new HttpClient();
client.BaseAddress = new Uri(string.Format("{0}/{1}/messages", @"https://api.mailgun.net/v3", "mailgundomain.mailgun.org"));
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "MailgunKeyGoesHere");
var kvpContent = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Content-Disposition: form-data; name=\"from\"", "Mailgun Sandbox <postmaster@mailgundomain.mailgun.org>"),
new KeyValuePair<string, string>("Content-Disposition: form-data; name=\"subject\"", "Test Email"),
new KeyValuePair<string, string>("Content-Disposition: form-data; name=\"text\"", "It Worked!!"),
new KeyValuePair<string, string>("Content-Disposition: form-data; name=\"to\"", "My Email <myemail@testdomain.co.uk>"),
};
var fileData = File.ReadAllBytes(@"C:\Temp\test.jpg");
//This is where it goes wrong. I know at the moment fileData.ToString() is wrong but this is the last thing I tried
kvpContent.Add(new KeyValuePair<string, string>("Content-Disposition: form-data; name=\"attachment\"; filename=\"test.jpg\" Content-Type: application/octet-stream",
fileData.ToString()));
var formContent = new FormUrlEncodedContent(kvpContent);
var response = client.PostAsync(client.BaseAddress, formContent).Result;
有什么想法吗?
【问题讨论】:
标签: c# email attachment mailgun