在Spring Boot中发送SendGrid电子邮件的最简单方法是使用SendGrid Java库。以下是详细步骤:
<dependency>
<groupId>com.sendgrid</groupId>
<artifactId>sendgrid-java</artifactId>
<version>4.7.0</version>
</dependency>
sendgrid.api-key=YOUR_SENDGRID_API_KEY
import com.sendgrid.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
@Value("${sendgrid.api-key}")
private String sendGridApiKey;
public void sendEmail(String to, String subject, String content) throws Exception {
Email from = new Email("your-email@example.com");
Email toEmail = new Email(to);
Content emailContent = new Content("text/plain", content);
Mail mail = new Mail(from, subject, toEmail, emailContent);
SendGrid sg = new SendGrid(sendGridApiKey);
Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
Response response = sg.api(request);
if (response.getStatusCode() != 202) {
throw new Exception("Failed to send email. Status code: " + response.getStatusCode());
}
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailController {
@Autowired
private EmailService emailService;
@GetMapping("/send-email")
public String sendEmail() {
try {
emailService.sendEmail("recipient@example.com", "Hello", "This is a test email.");
return "Email sent successfully.";
} catch (Exception e) {
return "Failed to send email: " + e.getMessage();
}
}
}
这样,当访问/send-email
接口时,将会发送一封包含"Hello"内容的测试邮件到"recipient@example.com"。
SendGrid是一家提供云端电子邮件服务的公司,其优势包括高可靠性、强大的邮件传递能力、灵活的API和丰富的功能。它适用于各种场景,如发送验证邮件、通知邮件、营销邮件等。
腾讯云提供了类似的电子邮件服务,称为腾讯云邮件推送(Email Delivery)。您可以通过腾讯云控制台或API来使用该服务。更多关于腾讯云邮件推送的信息,请访问腾讯云邮件推送产品介绍。
领取专属 10元无门槛券
手把手带您无忧上云