简体   繁体   中英

Simplest way to send a sendgrid email in spring boot

I am trying to send stacktrace emails in Spring. Here is what I have so far:

# application.properties
spring.sendgrid.api-key="SG.o1o9MNb_QfqpasdfasdfasdfpLX3Q"

And in my 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) {

    }

However, it seems like it's not initializing the SendGrid object correctly (with the API key from application.properties). What would be the correct way to do the above?

The SendGrid object should not be created explicitly, but it should be passed as a bean and in this case Spring will initialize it with the API key appropriately (check the code that is responsible for autoconfiguration). So it should look like this:

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

Latter you can use this service in your controller by injecting it, for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM