【问题标题】:SendGrid emailing API , send email attachmentSendGrid 电子邮件 API,发送电子邮件附件
【发布时间】:2016-11-30 15:28:31
【问题描述】:

我正在使用 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("test@example.com");
    String subject = "Hello World from the SendGrid Java Library!";

    Email to = new Email("shareef@gmail.com");
    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;
    }
  }

}

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

 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("shareef@gmail.com");
            String subject = "Hello World from the SendGrid Java Library!";

            Email to = new Email("shareef@gmail.com");
            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);
            }
        }

    }

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

【问题讨论】:

  • 您应该从代码示例中删除密钥
  • 是的,谢谢@IcedD​​ante,我放的是随机的,不是真实的,我会以任何方式重新随机的
  • 嗨,@shareef 你能告诉我一次可以发送多少封电子邮件,sendgrid 的 java sdk 有没有限制?
  • 嗨@OnkarMusale,您可以查看他们的网站以获取更新的信息文档,或者只是进行实时聊天,他们反应非常迅速!
  • @shareef 非常感谢您的回复,我刚刚发现我们可以每秒发送 10k 到 15k,但建议每秒发送 1k。

标签: java sendgrid


【解决方案1】:

当我执行代码时,我在 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}

解决此问题的技巧是使用 commons apache 编解码器 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 作为响应它起作用了

【讨论】:

  • 谢谢,但是随电子邮件发送的附件是完整的新表。就我而言,我想发送包含执行结果的数据的 excel。请让我知道如何将文件 excel 文件作为附件从本地系统发送
【解决方案2】:

这是您可以使用 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;
    }

【讨论】:

    【解决方案3】:

    它对我有用 (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);
    

    【讨论】:

    • 我猜应该是String attachmentContent = Base64.getEncoder().encodeToString(attachmentContentBytes);而不是String attachmentContent = Base64.getMimeEncoder().encodeToString(attachmentContentBytes);
    • @CodeTripper,当然。 From baeldung.com: "MIME 编码器使用基本字母表生成 Base64 编码的输出,但采用 MIME 友好的格式。输出的每一行不超过 76 个字符,并以回车符和换行符结尾(\r\n)"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    相关资源
    最近更新 更多