【问题标题】:Simplest way to send a sendgrid email in spring boot在 Spring Boot 中发送 sendgrid 电子邮件的最简单方法
【发布时间】:2018-07-27 20:21:39
【问题描述】:

我正在尝试在 Spring 中发送堆栈跟踪电子邮件。这是我目前所拥有的:

# application.properties
spring.sendgrid.api-key="SG.o1o9MNb_QfqpasdfasdfasdfpLX3Q"

在我的 ErrorController 中:

    // Send Mail
    Email from = new Email("david@no-reply.com");
    String subject = "Exception " + message.toString();
    Email to = new Email("tom@gmail.com");
    Content content = new Content("text/plain", trace);
    Mail mail = new Mail(from, subject, to, content);
    Request r = new Request();

    try {
        SendGrid sendgrid = new SendGrid();
        r.setMethod(Method.POST);
        r.setEndpoint("mail/send");
        r.setBody(mail.build());
        Response response = sendgrid.api(request);
        sendgrid.api(r);
    } catch (IOException ex) {

    }

但是,它似乎没有正确初始化 SendGrid 对象(使用来自 application.properties 的 API 密钥)。执行上述操作的正确方法是什么?

【问题讨论】:

  • Spring 会自动配置 SendGrid bean,你不应该自己创建它,而是作为 bean 注入。
  • @SergiiZhevzhyk 你能告诉我如何调用该方法吗?

标签: java spring spring-boot sendgrid


【解决方案1】:

SendGrid 对象不应显式创建,但应作为 bean 传递,在这种情况下,Spring 将使用 API 密钥适当地对其进行初始化(检查负责自动配置的 code)。所以它应该是这样的:

@Service
class MyMailService {

    private final SendGrid sendGrid;

    @Inject
    public SendGridMailService(SendGrid sendGrid) {
        this.sendGrid = sendGrid;
    }

    void sendMail() {
        Request request = new Request();
        // .... prepare request
        Response response = this.sendGrid.api(request);                
    }
}

之后你可以通过注入在你的控制器中使用这个服务,例如:

@Controller
public class ErrorController {

     private final emailService;

     public ErrorController(MyMailService emailService) {
           this.emailService = emailService;
     } 

     // Now it is possible to send email 
     // by calling emailService.sendMail in any method
}

【讨论】:

  • 谢谢。你如何从控制器调用它?如果我这样做:new MyMailService().sendMail(); 我收到一条错误消息,上面写着Error:(38, 9) java: constructor MyMailService in class com.test.login.MyMailService cannot be applied to given types; required: com.sendgrid.SendGrid found: no arguments reason: actual and formal argument lists differ in length
  • 您需要在错误控制器的构造函数中传递此服务,并用@Inject 标记此构造函数(与MyEmailService 中的SendGrid 相同)。
  • 感谢您提供的信息。您能否在回答中提供一个示例,我会继续接受吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 2018-07-05
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 2018-08-09
  • 1970-01-01
相关资源
最近更新 更多