如何使用sendgrid将PDF和WORD转换为base64编码并作为附件发送到电子邮件?

时间:2019-05-30 11:26:39

标签: c# sendgrid

我想使用sendgrid上传任何文本文件并将其作为附件发送到电子邮件。我也收到电子邮件和附件,但无法打开它,而.text文件类型可以按原样打开和查看。

下面,我正在创建sendgrid邮件,并将文件转换为base64并将其添加到sendgrid的AddAttachment中。

string body = EmailBody(taskRecord.Subject, customer.CustName, User.Identity.Name);
var client = new SendGridClient("APIKey");
                    var from = new EmailAddress("sender", "The SaharaCRM");
                    var to = new EmailAddress("reciepient", customer.CustName);
                    var htmlContent = body;
                    var msg = MailHelper.CreateSingleEmail(from, to, taskRecord.Subject, "", htmlContent);

//converting file to base64
files.FileName = Request.Files[0].FileName;
                    index = files.FileName.IndexOf('.');
                    files.FileType = files.FileName.Substring(index);
                    System.IO.Stream fs = Request.Files[0].InputStream;
                    System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
                    Byte[] bytes = br.ReadBytes((Int32)fs.Length);
                    string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);


//adding converted base64 file input stream to AddAttachment and sending.
msg.AddAttachment(files.FileName, base64String, files.FileType, "attachment", "banner");
var some =  client.SendEmailAsync(msg);

只能查看.text类型的文件,不能查看pdf和word类型的文件, 单击以打开“糟糕!预览此文档时出现问题”。当喜欢下载然后开始下载时,但是打开时出现错误 无法加载PDF文档。

0 个答案:

没有答案