Search code examples
google-app-enginesendgridsendgrid-api-v3

Send a PDF as an attachment through Sendgrid


I'm using Sendgrid to send emails through an app on GAE. It's working fine, but I also want to be able to send PDFs as an attachment. I'm not using Sendgrid.jar file in my project. I've just used Sendgrid.java. And this class has no methods by which i can add attachments. Can someone help me?


Solution

  • Here is the code of a servlet that sends a mail with a PDF as attachment, through Sendgrid:

        @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 is one of my classes in which getPDFOutputStream method returns the PDF as ByteArrayOutputStream.