HttpClient中的电子邮件附件



我目前正在使用Mailgun通过他们的REST API服务在我的应用程序中执行一些电子邮件发送。他们的例子使用RestSharp,它已经在我的项目中获得了MSWebneneneba API rest客户端,我不愿意为这个功能安装另一个。使用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:Temptest.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;

有什么想法吗?

我创建了MultipartFormDataContent而不是FormUrlEncodedContent,并在MultipartFormData对象上添加了内容。

您可以通过以下方式添加创建ByteArrayContent对象的附件:

ByteArrayContent fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                 {
                      Name = "attachment",
                      FileName = "MyAttachment.pdf"
                 };
content.Add(fileContent);

在content是我的MultipartFormDataContent对象的地方,我在关于HttpClient的HTTPPost方法中传递这个对象。例如:

HttpResponseMessage response = client.PostAsync(url, content).Result; 

我希望能帮上忙。

相关内容

  • 没有找到相关文章

最新更新