我正在使用sendgrid:4.1.2
发送邮件。我将图像附加到我的邮件中。当我收到邮件时,附加的图像没有打开,图像查看器说 - Premature end-of-file encountered
。我使用以下代码将文件附加到邮件对象:
/*Prepare the email to be sent*/
Mail mail = new Mail();
mail.addPersonalization(personalization);
mail.setFrom(from);
mail.setSubject(subject);
/*Prepare the attachments for the mail */
if (attachments != null && attachments.size() > 0) {
for (EmailAttachmentDo emailAttachmentDo : attachments) {
Attachments attachment = new Attachments();
attachment.setContent(new
String(Base64.getEncoder().encode(emailAttachmentDo.getContent())));
attachment.setType("IMAGE");
attachment.setFilename("image-name.png");
attachment.setDisposition("attachment");
attachment.setContentId(emailAttachmentDo.getContentId());
mail.addAttachments(attachment);
}
}
/*Make a send email request*/
Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sendGrid.api(request)
注意:将附加的图像内容编码到Base64字符串后,我得到了这个:
iVBORw0KGgoAAAANSUhEUgAAAVwAAACRCAMAAAC4yfDAAAAA+VBMVEX///8xdPHmMSX2rQEkmkEGlTMYlzpzt4ELZ/AgbfD2qgCtwvgqcfH1pgD2qwAmb/HkAADmLSAXavAAZfDlFwDlJhflIhG017vJ1/pnsnfb5PzlHwz4+v51nPTw9P7U3/t/ovX2wsD74uH98fCQrvadt/fvkY3858b5zoY2d/H87Ov52djn7f3B0fqlvfhslvTzr6z4z81ikPPwmJVDfvLpUUnnOzB6n/XypaLg6PzrbGboRj3tfXj0trROhPL60pH4xGr++O73uULqXFX615/8473++vLuh4L2siP73a/98t/4vlbsc21ZivP6z4mVyJ8AW+/I4c34wmK8ycgKAAAPPklEQVR4nO1deV/azBYWuH3fBIJZSLi8gCyyuAEKouKGVmxBW3t77/f/MDcEQs6smViDlc7zh/01ZODkycmZs81ka0tCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkLiT0G54qL83lJsHKqZ2uDAUhZIvNR6Bcnxm6DYGiuWqmuJFTRNtXLDZuG9Jfvo6DQTigp4BQzrll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ZxJmMQPeY5iG6zmPuJcrODI3TPLabhZk3hGpSn3+k8YV96eyM07cLZB9D3XADzdrChFE0958A/6F+V31igAswnZJx9uqKGkS1NVBdhlV13kTu/mMp1ksz+uvm+tNzY74Ri4u864mfjYQbK/b2U9msS/H2tvsnnX24E9gmZIFOby76HIp2sUrkU2yuABr19sQNf1wY9tm0/mtlHwSVajfTas7R61Zfvd9Fo3972p5O26N61GLf172nu30Xj1+EifVRqRYKhSLMTI9fRa6HxuHu7uEb8rp5AL1X7y3KxiFY8xOyvEYiOoIyJmdVigQbFU5DVrB3xx+5s+KvwvXPLfanQXQRstJZgkR3HlmyOzVBuyvnDkhQUO4lFoEZsykEhBUf/q03a0WnpgR6SQ9zakBxP/zbHdeKy58gkYBXoz3A+u+fuAvzr+ACdlxSvNjMejaz3Uwg27DoxIsxa0gvU+T0yJ8OZAMhDXlRS7mHFCik4kYHWllX1WahU650Lgu9gYKlz99b0g+IClbg0S1LmWcd8T3xcqEve5MgURDaypH3/kcJNohWTQo+/lsz3wu90K6QTXiz43uhm+OXrYnWUokIuExQC+sLaNSWcwlxNJnKa40/9Fvhfwt0dnKUngvdSshszVug0hoq6sq91XRVVRK1V+7sJUGi020OEm4QoVjqeKfVlfYgBsgMjYSEhISEhISEhISEhISEhISEhISEhITEpuD/wSBwxgUh+QAAAAAASUVORK5CYII=
解决这个问题的诀窍是使用commons apache codec commons-codec-1.8.jar及其encodeAsString
方法对包进行编码
org.apache.commons.codec.binary.Base64
Attachments attachments3 = new Attachments();
Base64 x = new Base64();
String imageDataString = x.encodeAsString(fileData);
attachments3.setContent(imageDataString);
attachments3.setType("image/png");//"application/pdf"
attachments3.setFilename("x.png");
attachments3.setDisposition("attachment");
attachments3.setContentId("Banner");
mail.addAttachments(attachments3);
即使内容长度作为响应它返回0也是如此。