在左导航栏选择Settings->API Keys,选择Create API Key,可根据需要选择权限,我选的是Full Access,点击生成后记得保存,这个key内容以后是查看不了的
发件人授权有两种方式,一种是配置域名(Domain Authentication),一种是单校验方式(Single Sender Verification)。域名的方式需要关联自己的二级域名,限于篇幅,感兴趣的朋友可以自行搜索,下图是配置的域名解析
我这里演示使用单校验即可,单击Verify a Single Sender配置即可
Reply To代表,收件人收到邮件后,点击回复到的邮箱地址,一般与发件人一致
在左导航栏选择Emial API->Integration Guide,可以看到集成send grid的演示
<!--sendgrid --> <dependency> <groupId>com.sendgrid</groupId> <artifactId>sendgrid-java</artifactId> <version>4.2.1</version> </dependency> <!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 复制代码
@Test public void testWebApi() { // 发件人,即配置的发件人邮箱地址 Email from = new Email("test@example.com"); // 邮件主题 String subject = "Sending with SendGrid is Fun"; // 收件人邮件地址 Email to = new Email("test@example.com"); // 邮件内容 Content content = new Content("text/plain", "and easy to do anywhere, even with Java"); Mail mail = new Mail(from, subject, to, content); // 配置API Keys的密钥 SendGrid sg = new SendGrid("SENDGRID_API_KEY"); Request request = new Request(); try { request.setMethod(Method.POST); request.setEndpoint("mail/send"); request.setBody(mail.build()); Response response = sg.api(request); System.out.println(response.getStatusCode()); System.out.println(response.getBody()); System.out.println(response.getHeaders()); } catch (IOException ex) { System.out.println(ex.getMessage()); } } 复制代码
查看收件箱
这里需要修改yml配置并引入mail依赖
spring: mail: host: smtp.sendgrid.net username: apikey password: 密钥内容 default-encoding: utf-8 port: 587 复制代码
测试
@Test public void sendSMTPRelay() { // 简单邮件类 SimpleMailMessage mailMessage = new SimpleMailMessage(); // 寄件人,默认是配置的username mailMessage.setFrom("test@example.com"); // 收件人,支持多个收件人 mailMessage.setTo("test@example.com"); // 邮件主题 mailMessage.setSubject("Test SMTP Relay mail"); // 邮件的文本信息 mailMessage.setText("Hello this is test mail from java 2"); // 发送邮件 mailSender.send(mailMessage); } 复制代码
查看收件箱
005.png
以下使用Web Api的方式发送验证码,smtp的模式可参考上面的示例替换
描述:发送用户名,根据用户名对应的邮箱地址,生成对应的验证码,有效期1min,1min内不生产新验证码
添加sendgrid与redis配置
spring: redis: database: 0 host: 120.79.27.209 port: 6379 password: sendgrid: from: name: chet email: api-key: 复制代码
验证码生成工具类
public static String randomAlphaNumeric(int count) { StringBuilder builder = new StringBuilder(); while (count-- != 0) { int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length()); builder.append(ALPHA_NUMERIC_STRING.charAt(character)); } return builder.toString(); } 复制代码
sendgrid的发送邮件服务
@Slf4j @Service public class SendGridService { /** * 发送邮件 */ public boolean sendMail(MailRequestForm requestForm) { SendGrid sg = new SendGrid(ConstantProperties.API_KEY); Request request = new Request(); Mail mail = buildMail(requestForm); try { request.setMethod(Method.POST); request.setEndpoint("mail/send"); request.setBody(mail.build()); Response response = sg.api(request); log.info("邮件发送结果: status code=[{}], body=[{}], headers= [{}]", response.getStatusCode(), response.getBody(), response.getHeaders()); } catch (IOException e) { log.error("邮件发送失败:[{}]", e.getMessage()); return false; } return true; } /** * 封装邮件参数 */ private Mail buildMail(MailRequestForm requestForm) { Mail mail = new Mail(); // from Email fromEmail = new Email(); fromEmail.setName(ConstantProperties.FROM_NAME); fromEmail.setEmail(ConstantProperties.FROM_EMAIL); mail.setFrom(fromEmail); // subject mail.setSubject(requestForm.getSubject()); // personalization Personalization personalization = new Personalization(); personalization.setSubject(requestForm.getSubject()); ReceiveUser receiveUsers = requestForm.getReceiveUsers(); List<MailInfoForm> toUserList = receiveUsers.getToUser(); if (toUserList != null && !toUserList.isEmpty()) { Email to = new Email(); toUserList.stream().forEach(i -> { to.setName(i.getName()); to.setEmail(i.getEmail()); // cc,bcc... 暂只使用直接发送 personalization.addTo(to); }); } mail.addPersonalization(personalization); // content ContentForm contentForm = requestForm.getContentForm(); Content content = new Content(); content.setType(contentForm.getType()); content.setValue(contentForm.getValue()); mail.addContent(content); // timestamp mail.setSendAt(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"))); return mail; } } 复制代码
详细过程,可参考源代码: github.com/chetwhy/clo…