java - 在 Spring Boot 中发送 sendgrid 电子邮件的最简单方法

标签 java spring spring-boot sendgrid

我正在尝试在 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 key )。执行上述操作的正确方法是什么?

最佳答案

不应显式创建 SendGrid 对象,但应将其作为 bean 传递,在这种情况下,Spring 将使用 API key 适本地初始化它(检查负责的 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);                
    }
}

稍后您可以通过注入(inject)在 Controller 中使用此服务,例如:

@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
}

关于java - 在 Spring Boot 中发送 sendgrid 电子邮件的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51565039/

相关文章:

java - 删除 xml 文件中的数据无法正常工作

Java Spring Data MongoDB 和 Java 8 时间

java - 带有空 URI 和 null Marshaller 的 Spring Web 服务请求

java - 无法使用 apache camel 3.4.3 和 Swagger 启动 Spring Boot 2.3.3

java - 查找月份的最后一天并在 Android 应用程序中使用值更改监听器

java - 错误 : java. lang.IllegalArgumentException:即使使用变通方法,比较方法也违反了其一般约定

java - Spring-boot swagger 在 io.swagger.models.parameters.Parameter 上抛出 java.lang.ClassNotFoundException

java - 无法在单元测试中使用自定义 Spring 转换器

java - JWindow 不出现

spring - 在 Spring JPA 中实现查询