【问题标题】:Sending email Attachment via SendGrid c# fails通过 SendGrid c# 发送电子邮件附件失败
【发布时间】:2017-05-03 14:31:18
【问题描述】:

我正在使用 Azure 移动服务后端,我可以通过 SendGrid 成功发送电子邮件。但是,每次我尝试添加附件时,它都会失败。我从来没有收到过电子邮件。经过一番研究,我发现我所需要的只是一条虚拟路径。我修改了路径名,还是不行。

我似乎无法弄清楚为什么会失败。

下面是我的代码:

var client = new SendGridClient("apiKey");

var msg = new SendGridMessage()
        {
            From = new EmailAddress(sender),
            Subject = "Adherence Report",
            PlainTextContent = "Sample Content ",
            HtmlContent = "<strong>Hello, Email!</strong>"
        };
            msg.AddTo(new EmailAddress(receipient, null));
            msg.AddAttachment(@"~\sample\adherence.csv", "Testing", null, null, null);

        var response = await client.SendEmailAsync(msg);

【问题讨论】:

  • "fails""does not work" 并没有给我们太多帮助 - 你有没有提出任何异常? SendGrid 管理界面中是否有任何问题的迹象?你检查过response的内容吗?
  • 可能重复。尝试使用 Server.MapPath 获取完整路径 stackoverflow.com/questions/37945281/…
  • @JamesThorpe,到目前为止没有引发异常,我在 SendGrid 界面中看不到任何问题。我已经打印出响应的正文,这就是我的“响应”:“System.Net.Http.StreamContent”、“文件”:“~\\sample\\adherence.txt”}}。
  • @PapaBurgundy 我按照您的建议进行了更改 - msg.AddAttachment(System.Web.HttpContext.Current.Server.MapPath(@"~\sample\adherence.csv"), "Testing",空,空,空); .即使在此更改之后,我仍然没有收到电子邮件。但是,如果我注释掉这一行,我会收到电子邮件。
  • 我从响应中打印出来的状态码值也表明这是一个 BadRequest。 “响应”:“BadRequest”,“文件”:“~\\sample\\adherence.txt”}}。我不确定在这种情况下我做错了什么。根据我看到的示例,我的代码似乎是正确的。

标签: c# sendgrid


【解决方案1】:

我检查了响应的内容并意识到这是失败的,因为计划的发送被取消并出现400 BAD REQUEST 错误。

经过一番研究,我从 SendGrid 网站上发现了这个链接 mail errors。在附件错误部分,他们解释说

附件内容必须是base64编码的。

这就是我的附件失败的原因。所以为了最终让它工作,我编辑了我的代码如下:

string sampleContent = Base64Encode("Testing");  // base64 encoded string
var client = new SendGridClient("apiKey");

var msg = new SendGridMessage()
    {
        From = new EmailAddress(sender),
        Subject = "Adherence Report",
        PlainTextContent = "Sample Content ",
        HtmlContent = "<strong>Hello, Email!</strong>"
    };
        msg.AddTo(new EmailAddress(recipient, null));
        msg.AddAttachment("myfile.csv", sampleContent, "text/csv", "attachment", "banner");

    var response = await client.SendEmailAsync(msg);

事实证明,这毕竟不是一个重复的问题,因为我在通过 SendGrid 发送电子邮件时遇到了另一种问题。文件名也可以按原样工作。我不需要拨打Server.MapPath

我能够成功接收带有附件的电子邮件。

【讨论】:

【解决方案2】:

试试这个:

var message = MailHelper.CreateSingleTemplateEmail(fromEmail, toEmail, "yourTemplateId", dictionaryWithVariablesToReplaceOnTemplate);

using var webClient = new WebClient();
webClient.Encoding = Encoding.UTF8;
var attachmentByteArray = webClient.DownloadData(attachmentFileUri);
var attachmentAsStringBase64 = Convert.ToBase64String(attachmentByteArray);
message.AddAttachment(attachmentFileName, attachmentAsStringBase64);

await client.SendEmailAsync(message);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 2014-03-03
    相关资源
    最近更新 更多