轻松发送邮件! springboot,sendgrid和greenmail

这是使用sendgrid电子邮件提供商的api的简短演示。 **克隆github存储库以获得更多详细信息! ** 我正在通过sendgrid Java客户端和在springboot制成的微服务中使用此api,并且像所有好的代码一样,它是经过测试的代码,让我们使用greenmail库模拟smtp服务器来接收电子邮件。

First of all you need to create an account in Sendgrid and enable an api Key to use in client.

There are some ways to use this sendgrid sdk and in this case will be approached the sending of e-mail that will be transferred by http connection in json format. There is another way to send an email, which would be to register a template in the administrative panel of sendgrid site and send it through the client with the key of the registered template. To do any invocation of sendgrid it is necessary to send the key, which is available in the sendgrid admin area.

要调用sendgrid api,必须构建请求对象,如下所示。

    public class RequestSendGridBuilder {
        private static final String MIME_TYPE_HTML = "text/html";
        private static final String ENDPOINT_MAIL_SEND = "mail/send";
        private Mail mail = new Mail();
        private Content content = new Content();
        public static RequestSendGridBuilder of() {
            return new RequestSendGridBuilder();
        }

        public RequestSendGridBuilder from(String from) {
            mail.setFrom(new Email(from));
            return this;
        }

        public RequestSendGridBuilder key(String key) {
            mail.addCustomArg("customerAccountNumber", key);
            return this;
        }

        public RequestSendGridBuilder content(String template) {
            content.setType(MIME_TYPE_HTML);
            content.setValue(template);
            return this;
        }

        public RequestSendGridBuilder subject(String subject) {
            mail.setSubject(subject);
            return this;
        }

        public RequestSendGridBuilder to(String to) {
            Personalization personalization = new Personalization();
            personalization.addTo(new Email(to));
            mail.addPersonalization(personalization);
            return this;
        }

        public Request build() throws IOException {
            mail.addContent(content);
            Request request = new Request();
            request.setMethod(Method.POST);
            request.setEndpoint(ENDPOINT_MAIL_SEND);
            request.setBody(mail.build());
            return request;
        }
    }

然后致电服务:

    @Override
    public EmailResponseDTO send(EmailRequestDTO request) throws EmailConnectionException {
        try {
            Request sendGridRequest = RequestSendGridBuilder.of()
                    .content(request.getContent())
                    .subject(request.getSubject())
                    .to(request.getTo())
                    .from(request.getFrom())
                    .key(sendGridKey)
                    .build();
            Response sendGridResponse = sendGrid.api(sendGridRequest);
            return getResponse(sendGridResponse, sendGridRequest);
        } catch (IOException e) {
            throw new EmailConnectionException(e);
        }
    }

是的,这很简单! 但不要忘记设置sendgrid API_KEY,否则它将无法正常工作。

Templates

只要您发送带有html内容的json,就可以使用自己的模板引擎。 在这种情况下,您将在项目中包含模板(例如html),并且需要进行更新以进行更新。

If you don't want to traffic large size of bytes over the network because of a very large email, it is possible, as previously said, to write your template in the administrative template panel, after creating the template, a key will be generated to identify it, and this key will be sent by the client to the service, so you do not have to traffic all the content of the email. In addition you will be able to update your template at runtime directly on the site https://sendgrid.com

    mail.setTemplateId(templateId);

    Request request = new Request();
    request.setMethod(Method.POST);
    request.setEndpoint(ENDPOINT_MAIL_SEND);
    request.setBody(mail.build());
    Response sendGridResponse = sendGrid.api(request);

Template parser parameters

在此示例中,我使用了胡子来将参数解析为模板。 它非常易于使用且非常高效。 要更改模板变量的值,只需将字符串映射传递到髭引擎,如下所示:

    public class TemplateService {
        private MustacheAutoConfiguration mustacheAutoConfiguration;

        public TemplateService(MustacheAutoConfiguration mustacheAutoConfiguration) {
            this.mustacheAutoConfiguration = mustacheAutoConfiguration;
        }

        public @NonNull String parseTemplateParams(EmailRequestDTO email) throws TemplateException {
            try {
                MustacheResourceTemplateLoader templateLoader = mustacheAutoConfiguration.mustacheTemplateLoader();
                Reader template = templateLoader.getTemplate(email.getTemplateName());
                return mustacheAutoConfiguration.mustacheCompiler(templateLoader)
                        .compile(template)
                        .execute(email.getTemplateParams());
            } catch (FileNotFoundException e) {
                throw new TemplateException("TEMPLATE_NOT_FOUND");
            } catch (MustacheException e) {
                throw new TemplateException("TEMPLATE_PARSE_ERROR", e);
            } catch (Exception e) {
                throw new TemplateException("GENERIC_ERROR", e);
            }
        }
    }

Test sending with a fake smtp mail server

要创建电子邮件集成测试,我正在使用greenmail库。 该库允许您创建一个伪造的smtp服务器,该服务器将接收客户端发送的电子邮件,因此可以保证更好的资格和实施效率。

  public static GreenMail getGreenMail() {
        if (greenMail == null) {
            ServerSetup serverSetup = new ServerSetup(
                    SocketUtils.findAvailableTcpPort(
                            INIT_RANGE_EMAIL_PORT,
                            END_RANGE_EMAIL_PORT),
                    ServerSetup.getLocalHostAddress(),
                    ServerSetup.PROTOCOL_SMTP);
            greenMail = new GreenMail(serverSetup);
            greenMail.setUser(
                    EMAIL_USER_ADDRESS,
                    USER_NAME,
                    USER_PASSWORD);
            greenMail.start();
        }
        return greenMail;
    }

Source code

To see the client working you can use the complete code here
ENJOY!!!

References

Http://www.icegreen.com/greenmail/
Https://sendgrid.com/docs/api-reference/

from: https://dev.to//georgeoikawa/send-mail-easily-springboot-sendgrid-and-greenmail-9g

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值