java SendGrid 电子邮件 API , 发送电子邮件附件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38599079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:34:19  来源:igfitidea点击:

SendGrid emailing API , send email attachment

javasendgrid

提问by shareef

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

我正在使用 sendgrid 发送电子邮件,使用以下代码可以正常工作,但没有附件。

package sendgrid;

import com.sendgrid.Content;
import com.sendgrid.Email;
import com.sendgrid.Mail;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import java.io.IOException;

public class SendEmail {
    public static void main(String[] args) throws IOException {
    Email from = new Email("[email protected]");
    String subject = "Hello World from the SendGrid Java Library!";

    Email to = new Email("[email protected]");
    Content content = new Content("text/plain", "Hello, Email!");
    Mail mail = new Mail(from, subject, to, content);

    SendGrid sg = new SendGrid("SG.rIEh84OgQBybYEJcOMie1wd.AZqqdWNYXbOqTarUJcG-iSg0UtHJtCto4oe6tVzn6es");
    Request request = new Request();
    try {

      request.method = Method.POST;
      request.endpoint = "mail/send";
      request.body = mail.build();

      Response response = sg.api(request);
      System.out.println(response.statusCode);
      System.out.println(response.body);
      System.out.println(response.headers);

    } catch (IOException ex) {
      throw ex;
    }
  }

}

But what i need is to send attachments with it so i searched github source and the web documentation API , and for some reason there is no javadocs but there was an example GitHub sendgridso am trying until it works , i narrowed down some exceptions and response code , at first i was getting unauthorized the forbidden and it got better to response 202 , means valid and queued (check here) any way here is my code that dose send an email and with attachments but when you open the attachment its zero size and says cannot open or preview the file !

但我需要的是用它发送附件,所以我搜索了 github 源和 web 文档 API,由于某种原因没有 javadocs 但有一个示例GitHub sendgrid所以我一直在尝试直到它工作,我缩小了一些例外和响应的范围代码,起初我得到了未经授权的禁止,它得到了更好的响应 202,意味着有效和排队(在这里检查)无论如何这里是我的代码,它会发送电子邮件和附件,但是当你打开附件时,它的大小为零说无法打开或预览文件!

 package sendgrid;

    import com.sendgrid.Attachments;
    import com.sendgrid.Content;
    import com.sendgrid.Email;
    import com.sendgrid.Mail;
    import com.sendgrid.MailSettings;
    import com.sendgrid.Method;
    import com.sendgrid.Request;
    import com.sendgrid.SendGrid;
    import com.sendgrid.Setting;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;


    public class SendEmailAttachmentV2 {

        public static void main(String[] args) throws IOException {
            sendmail();
        }

        // Fully populated Mail object
        public static void sendmail() throws IOException {

            com.sendgrid.Response response1;

            Email from = new Email("[email protected]");
            String subject = "Hello World from the SendGrid Java Library!";

            Email to = new Email("[email protected]");
            Content content = new Content("text/plain", "Hello, Email!");
            Mail mail = new Mail(from, subject, to, content);

            File file = new File("C:\x.png");
            byte[] fileData = null;
            try {
                fileData = org.apache.commons.io.IOUtils.toByteArray(new FileInputStream(file));
            } catch (IOException ex) {
            }

            Attachments attachments3 = new Attachments();            
            attachments3.setContent(new String(fileData, 0, (int) file.length(), "UTF-8"));
            attachments3.setType("image/png");//"application/pdf"
            attachments3.setFilename("x.png");
            attachments3.setDisposition("attachment");
            attachments3.setContentId("Banner");
            mail.addAttachments(attachments3);


            MailSettings mailSettings = new MailSettings();
            Setting sandBoxMode = new Setting();
            sandBoxMode.setEnable(true);
            mailSettings.setSandboxMode(sandBoxMode);

            SendGrid sg = new SendGrid("SG.1Hg78VK0TJ6kexUnByZUYg.LAa5A4GufssZ9lpPQdV6PcZCY6SZ9Xq6LvqfMRG0wesKw");
            Request request1 = new Request();
            try {
                request1.method = Method.POST;
                request1.endpoint = "mail/send";

                request1.body = mail.build();

                response1 = sg.api(request1);
                System.out.println(response1.statusCode);
                System.out.println(response1.body);
                System.out.println(response1.headers);

            } catch (IOException ex) {
                System.out.println(ex);
            }
        }

    }

FYI: use your generated API key that generated from the console of sendgrid

仅供参考:使用从 sendgrid 控制台生成的 API 密钥

采纳答案by shareef

When i executed the code i got the following message in logs in netbeans

当我执行代码时,我在 netbeans 的日志中收到以下消息

 202

 {X-Frame-Options=DENY, Server=nginx, Connection=keep-alive,
 X-Message-Id=vqVw2RtUShSVQ_ymVEVqaw, Content-Length=0, Date=Tue, 26
 Jul 2016 20:05:54 GMT, Content-Type=text/plain; charset=utf-8}

The trick to solve the issue is to encode the attachment using commons apache codec commons-codec-1.8.jarand itsencodeAsString` method from package

解决这个问题的技巧是使用包中的 commons apache 编解码器commons-codec-1.8.jarand itsencodeAsString` 方法对附件进行编码

org.apache.commons.codec.binary.Base64

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);

Even the content-length was retruned as 0 in response it worked.

甚至 content-length 也被重新返回为 0 以响应它的工作

回答by Nayan

This is the way you can send attachments using SendGrid API.

这是您可以使用 SendGrid API 发送附件的方式。

Mail mail = createEmail();
    Attachments attachments = new Attachments();
    Base64 x = new Base64();
    String encodedString = x.encodeAsString(loadPdfFromClasspath());
    attachments.setContent(encodedString);
    attachments.setDisposition("attachment");
    attachments.setFilename("xyx.pdf");
    attachments.setType("application/pdf");
    mail.addAttachments(attachments);


try {
        request.method = com.sendgrid.Method.POST;
        request.endpoint = "mail/send";
        request.body = mail.build();
        // Uncomment once connectivity with sendgrid is resolved
        Response response = sg.api(request);

}catch (IOException ex) {
        throw ex;
    }

回答by Taras Melnyk

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

它对我有用最新的 Maven 版本 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);