创建了SendGrid邮件模板,如何在Java中调用它?

8
我在SendGrid中创建了一个带有可替换值的电子邮件模板。
我从RabbitMQ队列中获取包含替代值的JSON负载以处理电子邮件。我的问题是如何从Java调用SendGrid电子邮件模板?

如何在Java中链接/调用以获取SendGrid邮件模板ID并发送邮件? - pjason
6个回答

4
我找到了解决方案,调用SendGrid模板并通过SendGrid发送电子邮件的方法如下:
SendGrid sendGrid = new SendGrid("username","password"));
SendGrid.Email email = new SendGrid.Email();

//Fill the required fields of email
email.setTo(new String[] { "xyz_to@gmail.com"});
email.setFrom("xyz_from@gmail.com");
email.setSubject(" ");
email.setText(" ");
email.setHtml(" ");

// Substitute template ID
email.addFilter(
    "templates",
    "template_id",
    "1231_1212_2323_3232");

//place holders in template, dynamically fill values in template
email.addSubstitution(
     ":firstName",
     new String[] { firstName });
email.addSubstitution(
     ":lastName",
     new String[] { lastName });

// send your email
Response response = sendGrid.send(email);

我正在使用最新版本的 sendgrid-java3.1.0)。Mail 类上都有 addFilteraddSubstitution 方法。有什么想法吗? - Jordi
https://github.com/sendgrid/sendgrid-java/blob/master/examples/helpers/mail/Example.java - Kiran Kumar

2
这是我的工作解决方案。
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sendgrid.*;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class MailUtil {
    public static void main(String[] args) throws IOException {
        Email from = new Email();
        from.setEmail("fromEmail");
        from.setName("Samay");
        String subject = "Sending with SendGrid is Fun";
        Email to = new Email();
        to.setName("Sam");
        to.setEmail("ToEmail");
        DynamicTemplatePersonalization personalization = new DynamicTemplatePersonalization();
        personalization.addTo(to);
        Mail mail = new Mail();
        mail.setFrom(from);
        personalization.addDynamicTemplateData("name", "Sam");
        mail.addPersonalization(personalization);
        mail.setTemplateId("TEMPLATE-ID");
        SendGrid sg = new SendGrid("API-KEY");
        Request request = new Request();
        try {
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());
            Response response = sg.api(request);
            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            throw ex;
        }
    }
    private static class DynamicTemplatePersonalization extends Personalization {

        @JsonProperty(value = "dynamic_template_data")
        private Map<String, String> dynamic_template_data;

        @JsonProperty("dynamic_template_data")
        public Map<String, String> getDynamicTemplateData() {
            if (dynamic_template_data == null) {
                return Collections.<String, String>emptyMap();
            }
            return dynamic_template_data;
        }

        public void addDynamicTemplateData(String key, String value) {
            if (dynamic_template_data == null) {
                dynamic_template_data = new HashMap<String, String>();
                dynamic_template_data.put(key, value);
            } else {
                dynamic_template_data.put(key, value);
            }
        }

    }
} 

3
虽然这段代码可能回答了问题,但是提供关于它如何解决问题、为什么能够解决问题的额外背景信息将会提高答案的长期价值。 - Nic3500

1
这是一个来自上一个API规范的例子:
import com.sendgrid.*;
import java.io.IOException;

public class Example {
  public static void main(String[] args) throws IOException {
    Email from = new Email("test@example.com");
    String subject = "I'm replacing the subject tag";
    Email to = new Email("test@example.com");
    Content content = new Content("text/html", "I'm replacing the <strong>body tag</strong>");
    Mail mail = new Mail(from, subject, to, content);
    mail.personalization.get(0).addSubstitution("-name-", "Example User");
    mail.personalization.get(0).addSubstitution("-city-", "Denver");
    mail.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932");

    SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
    Request request = new Request();
    try {
      request.setMethod(Method.POST);
      request.setEndpoint("mail/send");
      request.setBody(mail.build());
      Response response = sg.api(request);
      System.out.println(response.getStatusCode());
      System.out.println(response.getBody());
      System.out.println(response.getHeaders());
    } catch (IOException ex) {
      throw ex;
    }
  }
}

https://github.com/sendgrid/sendgrid-java/blob/master/USE_CASES.md


0
如果您正在进行一个 spring-boot 的maven项目,您需要在pom.xml中添加sendgrid-java的maven依赖。同样,在项目的resource文件夹下的application.properties文件中,添加SENDGRID API KEYTEMPLATE ID,并将其作为属性添加,例如:spring.sendgrid.api-key=SG.xyztemplateId=d-cabc
完成预设后,您可以创建一个简单的控制器类,如下所示:
祝您编码愉快!
@RestController
@RequestMapping("/sendgrid")
public class MailResource {

    private final SendGrid sendGrid;

    @Value("${templateId}")
    private String EMAIL_TEMPLATE_ID;

    public MailResource(SendGrid sendGrid) {
        this.sendGrid = sendGrid;
    }

    @GetMapping("/test")
    public String sendEmailWithSendGrid(@RequestParam("msg") String message) {

        Email from = new Email("bijay.shrestha@f1soft.com");
        String subject = "Welcome Fonesal Unit to SendGrid";
        Email to = new Email("birat.bohora@f1soft.com");
        Content content = new Content("text/html", message);

        Mail mail = new Mail(from, subject, to, content);

        mail.setReplyTo(new Email("bijay.shrestha@f1soft.com"));
        mail.setTemplateId(EMAIL_TEMPLATE_ID);

        Request request = new Request();
        Response response = null;


        try {
            request.setMethod(Method.POST);
            request.setEndpoint("mail/send");
            request.setBody(mail.build());

            response = sendGrid.api(request);

            System.out.println(response.getStatusCode());
            System.out.println(response.getBody());
            System.out.println(response.getHeaders());
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }

        return "Email was successfully sent";
    }

}

0

这是基于版本com.sendgrid:sendgrid-java:4.8.3的。

        Email from = new Email(fromEmail);
        Email to = new Email(toEmail);
        String subject = "subject";

        Content content = new Content(TEXT_HTML, "dummy value");

        Mail mail = new Mail(from, subject, to, content);

        // Using template to send Email, so subject and content will be ignored
        mail.setTemplateId(request.getTemplateId());

        SendGrid sendGrid = new SendGrid(SEND_GRID_API_KEY);
        Request sendRequest = new Request();

        sendRequest.setMethod(Method.POST);
        sendRequest.setEndpoint("mail/send");
        sendRequest.setBody(mail.build());

        Response response = sendGrid.api(sendRequest);

你还可以在这里找到完整的示例: Java完整的电子邮件对象示例


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接