使用sendgrid邮件助手时,附加到sendgrid api不起作用

时间:2016-10-17 17:31:39

标签: c# sendgrid

我已经查看了我在这里可以找到的关于将文件附加到sendgrid电子邮件的问题,但似乎没有问题我。

我的问题是这个。如何使用api发送包含sendgrid附件的电子邮件?

 dynamic sg = new SendGridAPIClient(apiKey);
        var from = new SendGrid.Helpers.Mail.Email("jkennedy@domain.com");
        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行。

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

此外,该文件的路径是c:\ tblaccudatacounts.csv

2 个答案:

答案 0 :(得分:2)

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

在您的示例中,您在添加附件之前调用var ret = mail.Get();。由于mail.Get()本质上是将邮件对象序列化为SendGrid期望的Json格式,因此在mail.Get()调用之后添加附件实际上不会将其添加到邮件对象中。

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

这是我的工作解决方案:

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

Email from = new Email("your@domain.com");
string subject = "Hello World from the SendGrid CSharp Library!";
Email to = new Email("destination@there.com");
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());

答案 1 :(得分:0)

我明白了。我正在使用第三方编写的帮手。我接受了SendGrid实际建议的内容。请参阅下面的代码,该代码现在正在运行。

var myMessage = new SendGridMessage {From = new MailAddress("info@email.com")};
        myMessage.AddTo("Jeff Kennedy <info@info.com>");
        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);