通过Sendgrid将PDF作为附件发送

时间:2017-03-20 09:53:07

标签: google-app-engine sendgrid sendgrid-api-v3

我正在使用Sendgrid通过GAE上的应用发送电子邮件。它工作正常,但我也希望能够将PDF作为附件发送。 我没有在我的项目中使用Sendgrid.jar文件。我刚刚使用了Sendgrid.java。而且这个类没有可以添加附件的方法。有人能帮助我吗?

3 个答案:

答案 0 :(得分:0)

我个人觉得直接构建JSON请求主体比API docs中描述的更容易,而不是使用Sendgrid的库。在我自己构造JSON数据之后,我只使用Sendgrid库来发送请求。

构建JSON数据时,您需要至少指定文件名和内容(即PDF文件)。在将PDF文件添加到JASON数据之前,请确保对其进行Base64编码。

我包含了一些代码,但是我使用Python而不是Java,所以不确定这会有所帮助。

答案 1 :(得分:0)

以下是通过Sendgrid发送带有PDF作为附件的邮件的servlet代码:

    @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    ....

    ByteArrayOutputStream os = null;
    try {
        PDFGenerator pdfGenerator = new PDFGenerator(invoiceOut);
        os = pdfGenerator.getPDFOutputStream();
    } catch (Exception e) {
        ....
    }

    SendGrid sendgrid = new SendGrid(Constants.SENDGRID_API_KEY);
    SendGrid.Email email = new SendGrid.Email();
    email.addTo(....);
    email.setFrom(....);
    email.setFromName(....);
    email.setSubject(....);
    email.setHtml("......");

    ByteBuffer buf = null;
    if (os == null) {
        //error...
    } else {
        buf = ByteBuffer.wrap(os.toByteArray());
    }

    InputStream attachmentDataStream = new ByteArrayInputStream(buf.array());

    try {
        email.addAttachment("xxxxx.pdf", attachmentDataStream);
        SendGrid.Response response = sendgrid.send(email);

    } catch (IOException e) {
        ....
        throw new RuntimeException(e);
    } catch (SendGridException e) {
        ....
        throw new RuntimeException(e);
    }

}

PDFGenerator是我的一个类,其中getPDFOutputStream方法将PDF作为ByteArrayOutputStream返回。

答案 2 :(得分:0)

public static boolean sendEmail(String fromMail, String title, String toMail, String message) throws IOException {
    Email from = new Email(fromMail);
    String subject = title;
    Email to = new Email(toMail);

    Content content = new Content("text/html", message);
    Mail mail = new Mail(from, subject, to, content);

    Path file = Paths.get("file path");
    Attachments attachments = new Attachments();
    attachments.setFilename(file.getFileName().toString());
    attachments.setType("application/pdf");
    attachments.setDisposition("attachment");

    byte[] attachmentContentBytes = Files.readAllBytes(file);
    String attachmentContent = Base64.getMimeEncoder().encodeToString(attachmentContentBytes);
    String s = Base64.getEncoder().encodeToString(attachmentContentBytes);
    attachments.setContent(s);
    mail.addAttachments(attachments);

    SendGrid sg = new SendGrid("sendgrid api key");
    Request request = new Request();

    request.setMethod(Method.POST);
    request.setEndpoint("mail/send");
    request.setBody(mail.build());
    Response response = sg.api(request);

    if (response != null) {
        return true;
    } else {
        return false;
    }
}

定义上述静态方法并根据程序需要使用相关参数进行调用。

相关问题