Java 在spring boot中发送sendgrid电子邮件的最简单方法

Java 在spring boot中发送sendgrid电子邮件的最简单方法,java,spring,spring-boot,sendgrid,Java,Spring,Spring Boot,Sendgrid,我试图在春天发送stacktrace电子邮件。以下是我到目前为止的情况: # application.properties spring.sendgrid.api-key="SG.o1o9MNb_QfqpasdfasdfasdfpLX3Q" 在我的错误控制器中: // Send Mail Email from = new Email("david@no-reply.com"); String subject = "Exception " + message.toStri

我试图在春天发送stacktrace电子邮件。以下是我到目前为止的情况:

# application.properties
spring.sendgrid.api-key="SG.o1o9MNb_QfqpasdfasdfasdfpLX3Q"
在我的错误控制器中:

    // 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键)。执行上述操作的正确方法是什么?

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

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

Spring自动配置SendGrid bean,您不应该自己创建它,而应该以bean的形式注入。@SergiiZhevzhyk您能告诉我如何调用该方法吗?谢谢。那么如何从控制器中调用它?如果我这样做:
newmymailservice().sendMail()我得到一个错误,上面写着
错误:(38,9)java:com.test.login.MyMailService类中的构造函数MyMailService不能应用于给定的类型;必需:com.sendgrid.sendgrid发现:无参数原因:实际参数列表和正式参数列表长度不同
您需要在错误控制器的构造函数中传递此服务,并使用@Inject标记此构造函数(与MyEmailService中对sendgrid的处理方式相同)。感谢提供此信息。请在你的回答中提供一个例子,我会接受的?