使用 SendGrid 发送带附件的电子邮件
Posted
技术标签:
【中文标题】使用 SendGrid 发送带附件的电子邮件【英文标题】:Sending an email with attachment using SendGrid 【发布时间】:2016-10-23 01:15:41 【问题描述】: var myMessage = new SendGridMessage();
myMessage.From = new MailAddress("info@email.com");
myMessage.AddTo("Cristian <myemail@email.com>");
myMessage.Subject = user.CompanyName + "has selected you!";
myMessage.html = "<p>Hello World!</p>";
myMessage.Text = "Hello World plain text!";
// myMessage.AddAttachment("C:\test\test.txt");
var apiKey = "";
var transportWeb = new Web(apiKey);
transportWeb.DeliverAsync(myMessage);
基本上我可以使电子邮件正常工作,而当我尝试添加附件时它不会发送它。我尝试了不同的路径和不同的路径编写方式,我不确定出了什么问题,我发现的每一个教程都表明它应该像这样工作。
【问题讨论】:
你有没有收到任何错误信息? 【参考方案1】:\
是转义字符
//用常规字符串字面量初始化。
myMessage.AddAttachment(@"C:\test\test.txt");
否则 // 用逐字字符串字面量初始化。
myMessage.AddAttachment("C:\\test\\test.txt");
【讨论】:
【参考方案2】:我让它工作了,结果我只需要一个虚拟路径:
myMessage.AddAttachment(Server.MapPath(@"~\img\logo.png"));
【讨论】:
【参考方案3】:使用 sendgrid 附加 blob 参考文档
mail.AddAttachment(AzureUploadFileClsName.MailAttachmentFromBlob("DocName20190329141433.pdf"));
您可以创建如下常用方法。
public static Attachment MailAttachmentFromBlob(string docpath)
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(storageContainer);
CloudBlockBlob blockBlob = container.GetBlockBlobReference(docpath);
blockBlob.FetchAttributes();
long fileByteLength = blockBlob.Properties.Length;
byte[] fileContent = new byte[fileByteLength];
for (int i = 0; i < fileByteLength; i++)
fileContent[i] = 0x20;
blockBlob.DownloadToByteArray(fileContent, 0);
return new Attachment Filename = "Attachmentname",
Content = Convert.ToBase64String(fileContent),
Type = "application/pdf",
ContentId = "ContentId" ;
【讨论】:
【参考方案4】:您可以添加多个文件
var msg = MailHelper.CreateSingleEmail(from, to, subject, null, content);
byte[] byteData = Encoding.ASCII.GetBytes(File.ReadAllText(filePath));
msg.Attachments = new List<SendGrid.Helpers.Mail.Attachment>
new SendGrid.Helpers.Mail.Attachment
Content = Convert.ToBase64String(byteData),
Filename = "FILE_NAME.txt",
Type = "txt/plain",
Disposition = "attachment"
;
【讨论】:
【参考方案5】:这是完整的例子:
static async Task ExecuteStreamAttachmentAdd()
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
var client = new SendGridClient(apiKey);
var from = new EmailAddress("test@example.com");
var subject = "Subject";
var to = new EmailAddress("test@example.com");
var body = "Email Body";
var msg = MailHelper.CreateSingleEmail(from, to, subject, body, "");
using (var fileStream = File.OpenRead("C:\\Users\\username\\file.txt"))
await msg.AddAttachmentAsync("file.txt", fileStream);
var response = await client.SendEmailAsync(msg);
【讨论】:
以上是关于使用 SendGrid 发送带附件的电子邮件的主要内容,如果未能解决你的问题,请参考以下文章
在“nodejs”中使用“@sendgrid/mail”发送“base64”电子邮件“附件”时遇到问题