在春季启动中发送sendgrid电子邮件的最简单方法

时间:2018-07-27 20:21:39

标签: java spring spring-boot sendgrid

我正在尝试在Spring中发送stacktrace电子邮件。这是我到目前为止的内容:

# 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密钥)。正确的方法是什么?

1 个答案:

答案 0 :(得分:2)

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
}