2016-10-17 42 views
0

我已经看过我可以在这里找到关于将文件附加到sendgrid电子邮件,但没有似乎有问题,我是我的问题。附加到sendgrid api不工作时使用sendgrid邮件助手

我的问题是这样的。如何使用api在sendgrid中发送附件中的附件?

dynamic sg = new SendGridAPIClient(apiKey); 
     var from = new SendGrid.Helpers.Mail.Email("[email protected]"); 
     var subject = "Hello World from the SendGrid C# Library!"; 
     var to = new SendGrid.Helpers.Mail.Email(toAddress); 
     var content = new Content("multipart/form-data", "Textual content"); 
     var attachment = new Attachment {Filename = attachmentPath }; 
     var mail = new Mail(from, subject, to, content); 

     var ret = mail.Get(); 

     mail.AddAttachment(attachment); 


     dynamic response = await sg.client.mail.send.post(requestBody: ret); 

如果我把mail.attachment放到邮件发送后但没有附件。如果我把addattachment行放在get之前,我得到一个“坏请求”消息。

我还没有找到具体如何做到这一点的例子。

此外,文件路径为c:\ tblaccudatacounts.csv

回答

0

我看着办吧。我正在使用由第三方编写的帮手。我使用SendGrid实际上建议的内容。看到下面的代码现在正在工作。

var myMessage = new SendGridMessage {From = new MailAddress("[email protected]")}; 
     myMessage.AddTo("Jeff Kennedy <[email protected]>"); 
     myMessage.Subject = "test email"; 
     myMessage.Html = "<p>See Attachedment for Lead</p>"; 
     myMessage.Text = "Hello World plain text!"; 
     myMessage.AddAttachment("C:\\tblaccudatacounts.csv"); 
     var apiKey = "apikey given by sendgrid"; 
     var transportWeb = new Web(apiKey); 
     await transportWeb.DeliverAsync(myMessage); 
+1

你从哪里得到这个代码示例?官方API网址https://github.com/sendgrid/sendgrid-csharp建议上面提到的@ DStage31。 –

+0

var transportWeb = new Web(apiKey); 什么是网络的声明? – Fuzzybear

+0

SendGrid.Web.Web – jeffkenn

2

经过几个小时的努力,我找到了一个使用sendgrid的V3 API的答案。这是我学到的东西。

在你的榜样,你添加附件之前调用var ret = mail.Get();。由于mail.Get()基本上是序列化的邮件对象为JSON格式SendGrid期待,加入mail.Get()呼叫之后的佩戴也不会真正把它添加到邮件对象。

你应该知道的另一件事是,API不具有简单地把文件路径作为输入的方式(至少我能找到,我希望有人能指正)。您需要手动设置至少内容(作为基本64字符串)和文件名。你可以找到更多的信息here

这是我工作的解决方案:

string apiKey = "your API Key"; 
dynamic sg = new SendGridAPIClient(apiKey); 

Email from = new Email("[email protected]"); 
string subject = "Hello World from the SendGrid CSharp Library!"; 
Email to = new Email("[email protected]"); 
Content body = new Content("text/plain", "Hello, Email!"); 
Mail mail = new Mail(from, subject, to, body); 

byte[] bytes = File.ReadAllBytes("C:/dev/datafiles/testData.txt"); 
string fileContentsAsBase64 = Convert.ToBase64String(bytes); 

var attachment = new Attachment 
{ 
    Filename = "YourFile.txt", 
    Type = "txt/plain", 
    Content = fileContentsAsBase64 
}; 

mail.AddAttachment(attachment); 

dynamic response = await sg.client.mail.send.post(requestBody: mail.Get()); 
+0

是的,它们已经引入了这个Base64编码的数据用于附件。在此之前,它曾经工作得很好。 –