使用SendGrid发送CSV附件异常:附件内容显示在邮件正文中
通过SendGrid(发件邮箱为Gmail.com)发送带CSV附件的邮件时,文件内容直接显示在正文里,而非附件形式,示例如下:
Please find attached the monthly statement of MAY2023.csv --frontier Content-Type: text/csv; charset="UTF-8" Content-Disposition: attachment; filename=MAI2023.csv 1,5,2023,0,0,10,V.Inst.,0.00,0.00 1,5,2023,0,0,26,V.Inst.,0.00,0.00 1,5,2023 ,0,0,41,V.Inst.,0.00,0.00 1.5,2023,0,0.57,V.Inst.,0.00,0.00 1.5,2023,0,1,12,V.Inst.,0.00,0.00 1.5 ,2023,0,1,27,V.Inst.,0.00,0.00 1.5,2023,0,1.43,V.Inst.,0.00,0.00 1.5,2023,0,1.58,V.Inst.,0.00 0.00 1,5,2023,0,2,13,V.Inst.......
直接使用laposte.net这类ISP发送时正常,邮件由Arduino设备通过Renzo Mischianti的EMailSender2库发送,相关代码如下:
/* sendgrid */ uint16_t SMTP_PORT2 = 587; const char* smtp_server2 = "smtp.sendgrid.net"; const char* email_login2 = "apikey"; const char* email_from2 = "myadress@gmail.com"; const char* name_from2 =expediteur.c_str(); const char* email_password2 = "SG...............d2sq4hXfg"; const char* arrayOfEmail[] = {"sendgridtesting@gmail.com" }; byte nb_Destinaire_Mail = 1; EMailSender::FileDescriptior fileDescriptor[piecejointe]; fileDescriptor[0].filename = NomFichierMensuel; fileDescriptor[0].url = NomFichierMensuel; fileDescriptor[0].mime = "text/csv"; fileDescriptor[0].encode64 = false; fileDescriptor[0].storageType = EMailSender::EMAIL_STORAGE_TYPE_SD; EMailSender::Attachments attachs = {piecejointe, fileDescriptor};
核心原因:参数设置不符合SendGrid要求
代码中encode64 = false的设置是问题根源。SendGrid的SMTP服务器要求附件必须经过Base64编码才能正确解析MIME结构,未编码的附件内容会被当作邮件正文的一部分输出。而laposte.net的SMTP服务器对未编码附件兼容性更高,所以直接发送正常。解决方法
将代码中的fileDescriptor[0].encode64 = false;修改为fileDescriptor[0].encode64 = true;,强制对CSV附件进行Base64编码。修改后SendGrid就能正确识别邮件的MIME边界,将CSV内容作为附件处理。排除其他可能性
不是Gmail的问题——Gmail支持标准MIME格式附件;也不是SendGrid故障——SendGrid遵循SMTP/MIME规范,问题出在客户端发送的邮件格式不符合其要求。
内容的提问来源于stack exchange,提问作者MGNTHE54

