gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:05:12 25 4
gpt4 key购买 nike

我正在尝试在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com