SendGrid emailing API , send email attachment

前端 未结 3 1142
你的背包
你的背包 2021-01-01 20:15

Am using sendgrid to send emails and it works fine using the following code but its without attachment.

package sendgrid;

import com.sendgrid.Content;
impor         


        
3条回答
  •  借酒劲吻你
    2021-01-01 20:46

    It works for me (the latest maven version SendGrid Java » 4.4.1):

            import com.sendgrid.helpers.mail.objects.Attachments;
            import com.sendgrid.helpers.mail.objects.Content;
            import com.sendgrid.helpers.mail.objects.Email;
            import com.sendgrid.helpers.mail.Mail;
    
            ......
    
            Content content = new Content("text/html", body);
            Mail mail = new Mail(from, subject, to, content);
            Path file = Paths.get(filePath);
            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);
            attachments.setContent(attachmentContent);
            mail.addAttachments(attachments);
    
            SendGrid sg = new SendGrid(apiKey);
            Request request = new Request();
    
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());
            Response response = sg.api(request);
    

提交回复
热议问题