我正在使用 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);
请您参考如下方法:
我检查了响应的内容并意识到这是失败的,因为预定的发送被取消并出现 400 BAD REQUEST 错误。
经过一些研究,我找到了这个链接 mail errors来自 SendGrid 网站。在附件错误部分,他们解释说
The attachment content must be base64 encoded.
这就是我的附件失败的原因。所以为了最终让它工作,我按如下方式编辑了我的代码:
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。
我能够成功接收带附件的电子邮件。
