2016-10-17 11 views
0

私はsendgrid電子メールにファイルを添付することについて私が見つけることができる質問を見てきましたが、私には問題はないようです。sendgrid mail helperを使用しているときにsendgrid apiが動作しない

私の質問はこれです。 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行を取得する前に「bad request」メッセージが表示されたら、

これを行う方法の例はまだありません。

はまた、ファイルへのパスは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 URL https://github.com/sendgrid/sendgrid-csharpは、@ DStage31が何を提案したかを示しています。 –

+0

var transportWeb =新しいWeb(apiKey); Webの宣言は何ですか? – 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

はい、V3から、このBase64でエンコードされたデータを添付して導入しました。それ以前は、うまく動作していました。 –

関連する問題