[英]Simplest way to send a sendgrid email in spring boot
我正在尝试在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密钥)。 做上述事情的正确方法是什么?
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.