All Projects → ozimov → Spring Boot Email Tools

ozimov / Spring Boot Email Tools

Licence: apache-2.0
A set of services and tools for sending emails in a Spring Boot 1.5.x application using a Template Engine

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to Spring Boot Email Tools

Spring Boot Examples
个人学习 SpringBoot2.x 写的一些示例程序,目前正在持续更新中.....
Stars: ✭ 159 (-3.05%)
Mutual labels:  freemarker, redis, spring-boot, thymeleaf
Springbootunity
rabbitmq、redis、scheduled、socket、mongodb、Swagger2、spring data jpa、Thymeleaf、freemarker etc. (muti module spring boot project) (with spring boot framework,different bussiness scence with different technology。)
Stars: ✭ 845 (+415.24%)
Mutual labels:  freemarker, redis, spring-boot, thymeleaf
Lovinghome Real Estate Platform
⚡️基于springboot+MyBatis+FreeMarker+redis+nginx+Echarts+druid等技术的JavaWeb项目------恋家房产平台(采用B/S架构,项目包含前后台,分为前台展示系统及后台管理系统。前台系统包含首页门户、登录注册、房产推荐、房产详情、热门房产、房产及小区搜索、经纪人列表及经纪机构创建、创建房产、房产百科、地图找房、用户个人中心、房产评论、房产打分等模块。 后台管理系统包含房产信息管理、用户管理、管理员管理、小区信息管理、博客管理、评论管理、经纪人管理、系统统计与多种图表展示、数据报表导入导出等模块。系统介绍及详细功能点、技术点见项目内文档描述)
Stars: ✭ 140 (-14.63%)
Mutual labels:  freemarker, redis, spring-boot
Spring boot
Spring Boot 使用总结 和 demo。 如果您觉得本代码对您有所帮助,请点击页面右上方"Star"
Stars: ✭ 431 (+162.8%)
Mutual labels:  redis, spring-boot, thymeleaf
Eshop Soa
EShop基于Dubbo实现SOA服务化拆分,并基于RocketMQ解决了分布式事务(新版SpringBootSOASkeleton)
Stars: ✭ 65 (-60.37%)
Mutual labels:  redis, spring-boot, thymeleaf
Hope Boot
🌱 Hope-Boot 一款现代化的脚手架项目
Stars: ✭ 3,241 (+1876.22%)
Mutual labels:  redis, spring-boot, thymeleaf
Spring Boot Projects
该仓库中主要是 Spring Boot 的入门学习教程以及一些常用的 Spring Boot 实战项目教程,包括 Spring Boot 使用的各种示例代码,同时也包括一些实战项目的项目源码和效果展示,实战项目包括基本的 web 开发以及目前大家普遍使用的线上博客项目/企业大型商城系统/前后端分离实践项目等,摆脱各种 hello world 入门案例的束缚,真正的掌握 Spring Boot 开发。
Stars: ✭ 4,022 (+2352.44%)
Mutual labels:  redis, spring-boot, thymeleaf
Javaquarkbbs
基于Spring Boot实现的一个简易的Java社区
Stars: ✭ 755 (+360.37%)
Mutual labels:  redis, spring-boot, thymeleaf
Thymeleaf Spring
Thymeleaf integration module for Spring
Stars: ✭ 349 (+112.8%)
Mutual labels:  spring-boot, thymeleaf, template-engine
Fxshop
基于SpringBoot+SpringCloud微服务的商城项目(demo版 不可用于生产)
Stars: ✭ 82 (-50%)
Mutual labels:  redis, spring-boot, thymeleaf
Jeeplatform
一款企业信息化开发基础平台,拟集成OA(办公自动化)、CMS(内容管理系统)等企业系统的通用业务功能 JeePlatform项目是一款以SpringBoot为核心框架,集ORM框架Mybatis,Web层框架SpringMVC和多种开源组件框架而成的一款通用基础平台,代码已经捐赠给开源中国社区
Stars: ✭ 1,285 (+683.54%)
Mutual labels:  freemarker, redis, thymeleaf
Aeromock
Lightweight mock web application server
Stars: ✭ 152 (-7.32%)
Mutual labels:  freemarker, thymeleaf, template-engine
Blog
一款简洁响应式博客系统
Stars: ✭ 72 (-56.1%)
Mutual labels:  redis, spring-boot, thymeleaf
Spring Cloud Microservices Development
Spring Cloud Microservices Development.《Spring Cloud 微服务架构开发实战》
Stars: ✭ 106 (-35.37%)
Mutual labels:  redis, spring-boot, thymeleaf
Spring Boot Leaning
Spring Boot 2.X 最全课程代码
Stars: ✭ 2,008 (+1124.39%)
Mutual labels:  redis, spring-boot, thymeleaf
Sk Admin
基于 Spring Boot、 Spring Data JPA、 Spring Security、Vue 的前后端分离的管理系统。项目采用模块开发方式, 主要模块:权限管理 (RBAC(Role-Based Access Control,基于角色的访问控制),支持数据字典、数据权限管理、前端菜单支持动态路由)、日志管理、代码生成器、系统监控、云存储管理、系统工具等等
Stars: ✭ 130 (-20.73%)
Mutual labels:  redis, spring-boot
Spring Boot Quick
🌿 基于springboot的快速学习示例,整合自己遇到的开源框架,如:rabbitmq(延迟队列)、Kafka、jpa、redies、oauth2、swagger、jsp、docker、spring-batch、异常处理、日志输出、多模块开发、多环境打包、缓存cache、爬虫、jwt、GraphQL、dubbo、zookeeper和Async等等📌
Stars: ✭ 1,819 (+1009.15%)
Mutual labels:  redis, spring-boot
Spring Boot Study
about learning Spring Boot via examples. 基于 spring boot 2.x 的学习教程简洁易懂
Stars: ✭ 131 (-20.12%)
Mutual labels:  spring-boot, thymeleaf
Nimrod
Nimrod - 基于 Spring Boot 构建 的 Java Web 平台企业级单体应用快速开发框架,适合中小型项目的应用和开发。所采用的技术栈包括 Spring Boot、Spring、Spring Web MVC、MyBatis、Thymeleaf 等,遵守阿里巴巴 Java 开发规约,帮助养成良好的编码习惯。整体采用 RBAC ( Role-Based Access Control ,基于角色的访问控制),具有严格的权限控制模块,支持系统与模块分离开发。最后希望这个项目能够对你有所帮助。Nimrod 开发交流群:547252502(QQ 群)
Stars: ✭ 125 (-23.78%)
Mutual labels:  spring-boot, thymeleaf
Jiiiiiin Security
一个前后端分离的内管基础项目
Stars: ✭ 132 (-19.51%)
Mutual labels:  redis, spring-boot

Spring Boot Email Tools

A set of services and tools for sending emails in a Spring Boot application using plain text, html or a template engine to generate dynamic content.

Source Website: github.com/ozimov/spring-boot-email-tools

Latest Release: 0.6.3
Latest Artifacts: it.ozimov:spring-boot-email-core, it.ozimov:spring-boot-freemarker-email, it.ozimov:spring-boot-mustache-email, it.ozimov:spring-boot-pebble-email, it.ozimov:spring-boot-thymeleaf-email
Continuous Integration:
Maven Central
Build Status codecov.io Codacy Badge

codecov.io

Background

The project relies on a templateless module it.ozimov:spring-boot-email-core that provides the core features (e.g. sending emails, scheduling and prioritizing, persistence). Since it is templateless, it does not provide any implementation of the service to be used to generate the body of the email via template engine.

If you want to use one of the template engines supported by this project (i.e. Freemarker, Mustache, Pebble and Thymeleaf), you can use the dedicated templatefull module that is shipped with the core module. The standard naming for the templatefull module is it.ozimov:spring-boot-{template_engine_name}-email (where {template_engine_name} is for instance pebble).

Dependency

Latest release is 0.6.3. To use the core module, you can import the following dependency in Maven

<dependency>
    <groupId>it.ozimov</groupId>
    <artifactId>spring-boot-email-core</artifactId>
    <version>0.6.3</version>
</dependency>

To embed the module that includes the Freemarker template engine, you can use the following Maven dependency:

<dependency>
    <groupId>it.ozimov</groupId>
    <artifactId>spring-boot-freemarker-email</artifactId>
    <version>0.6.3</version>
</dependency>

for Mustache:

<dependency>
    <groupId>it.ozimov</groupId>
    <artifactId>spring-boot-mustache-email</artifactId>
    <version>0.6.3</version>
</dependency>

for Pebble:

<dependency>
    <groupId>it.ozimov</groupId>
    <artifactId>spring-boot-pebble-email</artifactId>
    <version>0.6.3</version>
</dependency>

and for Thymeleaf:

<dependency>
    <groupId>it.ozimov</groupId>
    <artifactId>spring-boot-thymeleaf-email</artifactId>
    <version>0.6.3</version>
</dependency>

Remember that if you import the template-full module, the core module should not be required.

Usage

In your main Spring Boot application, you need to add the annotation @EnableEmailTools to enable support for all the services and controllers defined in the Spring Boot Email module, e.g.:

@SpringBootApplication
@EnableEmailTools
public class MainApplication  {

    public static void main(final String ... args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

in you application.properties set the configuration needed to send the emails, e.g. if you want to send the emails using a Gmail account you can set:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=[email protected]
spring.mail.password=V3ry_Str0ng_Password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

Plus, the additional properties must be added to prevent using the persistence layer

spring.mail.scheduler.persistence.enabled=false
spring.mail.scheduler.persistence.redis.embedded=false
spring.mail.scheduler.persistence.redis.enabled=false

To send an email, use the EmailService in your Spring Boot application. E.g.

@Autowired
public EmailService emailService;

public void sendEmailWithoutTemplating(){
   final Email email = DefaultEmail.builder()
        .from(new InternetAddress("[email protected]", "Marco Tullio Cicerone "))
        .to(Lists.newArrayList(new InternetAddress("[email protected]", "Pomponius Attĭcus")))
        .subject("Laelius de amicitia")
        .body("Firmamentum autem stabilitatis constantiaeque eius, quam in amicitia quaerimus, fides est.")
        .encoding("UTF-8").build();

   emailService.send(email);
}

The previous code will send a plain text message. To obtain some more dynamic fancy emails, you have two options: i) the former and easier-to-use is to use a templatefull module (e.g. based on Freemarker); ii) the latter (which requires some effort on your side) needs an implementation of the interface it.ozimov.springboot.templating.mail.service.TemplateService.

The aforementioned interface requires a component that implements the following method

String mergeTemplateIntoString(String templateReference, Map<String, Object> model)
            throws IOException, TemplateException;

Assuming you opted for one of the previous options, just put the template in the required folder (e.g. templates under resourses) and try to execute the following code (it works with Freemarker):

@Autowired
public EmailService emailService;

public void sendEmailWithTemplating(){
   Arrays.asList(new Cospirator("[email protected]", "Gaius Cassius Longinus"),
            new Cospirator("[email protected]", "Marcus Iunius Brutus Caepio"))
        .stream.forEach(tyrannicida -> {
       final Email email = DefaultEmail.builder()
            .from(new InternetAddress("[email protected]", "Gaius Iulius Caesar"))
            .to(Lists.newArrayList(new InternetAddress(tyrannicida.getEmail(), tyrannicida.getName())))
            .subject("Idus Martii")
            .body("")//Empty body
            .encoding("UTF-8").build();
        //Defining the model object for the given Freemarker template
        final Map<String, Object> modelObject = new HashMap<>();
        modelObject.put("tyrannicida", tyrannicida.getName());

       emailService.send(email, "idus_martii.ftl", modelObject);
   };
}

private static class Cospirator {
  private String email;
  private String name;
  public Cospirator(final String email, final String name){
    this.email = email;
    this.name = name;
  }

  //getters
}

where the template idus_martii.ftl is a Freemarker file like:

<!doctype html>
<html>
	<body>
		<p>
			Tu quoque, <em>${tyrannicida}</em>!
		</p>
	</body>
</html>

The following example shows how to send and email that includes an inline image.

@Autowired
public EmailService emailService;

public void sendEmailWithTemplatingAndInlineImage(){
       final Email email = DefaultEmail.builder()
            .from(new InternetAddress("[email protected]", "Gaius Iulius Caesar"))
            .to(Lists.newArrayList(new InternetAddress("[email protected]", "Marcus Iunius Brutus Caepio")))
            .subject("Idus Martii")
            .body("")//Empty body
            .encoding("UTF-8").build();
       //Defining the model object for the given Freemarker template
       final Map<String, Object> modelObject = new HashMap<>();
       final File imageFile = //load your picture here, e.g. "my_image.jpg"
       modelObject.put("tyrannicida", tyrannicida.getName());

       final InlinePicture inlinePicture = DefaultInlinePicture.builder()
                               .file(imageFile)
                               .imageType(ImageType.JPG)
                               .templateName("my_image.jpg").build());

       emailService.send(email, "idus_martii.ftl", modelObject, inlinePicture);
}

where the template idus_martii.ftl is a Freemarker file like:

<!doctype html>
<html>
	<body>
		<p>
			<img src="my_image.jpg" />
		</p>
	</body>
</html>

be sure that the name provided in the InlinePicture matches with the one used in the template file path included, if any was set. This means that if in the template you have <img src="images/my_image.jpg" /> then the definition has to be changed as follows:

final InlinePicture inlinePicture = DefaultInlinePicture.builder()
        .file(imageFile)
        .imageType(ImageType.JPG)
        .templateName("images/my_image.jpg").build());

This is required to set the a proper content-id.

Email scheduling

The library supports email scheduling, but since version 0.6.3 the scheduler is disabled by default. To enable email scheduling, the following property has to be provided:

spring.mail.scheduler.enabled=true

Email can be set in different queues, from the one with highest priority to the least important. Priority 1 is the highest.

To define the number of priority levels to be used in the scheduler, just add in the application.properties the following line:

spring.mail.scheduler.priorityLevels=5

If not provided, by default 10 priority levels are considered.

Scheduling an email is actually easy and the EmailSchedulerService allows to schedule an email with or without the use of a template engine.

In order to schedule a plain text email, just create your service (or controller) where you autowire the service EmailSchedulerService and call a method scheduleEmail defined as in the following example

@Service
public void MyEmailSenderService {

    @Autowired
    private EmailSchedulerService EmailSchedulerService;
    
    
    public void scheduleEmail() throws CannotSendEmailException {
        final Email mimeEmail = DefaultEmail.builder()
                                  .from(new InternetAddress("[email protected]", "Gaius Iulius Caesar"))
                                  .to(Lists.newArrayList(new InternetAddress(tyrannicida.getEmail(), tyrannicida.getName())))
                                  .subject("Idus Martii")
                                  .body("Sic semper...")
                                  .encoding("UTF-8")
                                  .build();
        final OffsetDateTime scheduledDateTime = OffsetDateTime.now().plusDays(1);
        final int priorityLevel = 1;
      EmailSchedulerService.schedule(mimeEmail, scheduledDateTime, priorityLevel);
    }
}

Here we go, by calling schedulerEmail() an email has been scheduled to be sent after one day. When scheduling emails, observe that OffsetDateTime must be used with UTC, so do not forget to convert it if you use a different zone offset.

To schedule an email with a template and inline images, just call a new method called scheduleEmailWithTemplate()

@Service
public void MyEmailWithTemplateSenderService {

    @Autowired
    private EmailSchedulerService EmailSchedulerService;
    
    
    public void scheduleEmailWithTemplate() throws CannotSendEmailException {
        final Email mimeEmail = DefaultEmail.builder()
                                  .from(new InternetAddress("[email protected]", "Gaius Iulius Caesar"))
                                  .to(Lists.newArrayList(new InternetAddress(tyrannicida.getEmail(), tyrannicida.getName())))
                                  .subject("Idus Martii")
                                  .body("")//Empty body
                                  .encoding("UTF-8")
                                  .build();
       //Defining the model object for the given Freemarker template
       final Map<String, Object> modelObject = new HashMap<>();
       final File imageFile = //load your picture here, e.g. "my_image.jpg"
       modelObject.put("tyrannicida", tyrannicida.getName());

       final InlinePicture inlinePicture = DefaultInlinePicture.builder()
                               .file(imageFile)
                               .imageType(ImageType.JPG)
                               .templateName("my_image.jpg").build();
        final OffsetDateTime scheduledDateTime = OffsetDateTime.now().plusDays(1);
        final int priorityLevel = 1;
      
        EmailSchedulerService.schedule(mimeEmail, scheduledDateTime, priorityLevel, 
            "idus_martii.ftl", modelObject, inlinePicture);
    }
    
}

Persistence

Persistence has been introduced in version 0.4.0. Persistence is mainly of interest if the scheduler is used, therefore it can be enabled only if the scheduler is enabled.

The persistence layer is optional, thus needs to be activated. The default implementation is fully based on embedded REDIS. To enable the default persistence layer just add the additional properties in your application.properties file:

spring.mail.scheduler.persistence.enabled=true
spring.mail.scheduler.persistence.redis.enabled=true
spring.mail.scheduler.persistence.redis.embedded=true
spring.mail.scheduler.persistence.redis.host=localhost
spring.mail.scheduler.persistence.redis.port=6381
spring.mail.scheduler.persistence.redis.settings=

I recommend to specify in the REDIS settings at least the appendfilename and dir properties, so that you know where the append file is placed and which name it uses. For instance do:

spring.mail.scheduler.persistence.redis.settings=appendfilename email_appendonly.aof, dir /Users/your_username/Downloads

By default we have the setting appendonly yes and appendfsync everysec. Feel free to override them or fine tune them according with your needs.

Clearly, you can provide your own persistence layer by implementing the PersistenceService interface. You can also use your REDIS implementation, but this will require extra coding on your side.

Observe that the persistence layer makes the emails being stored to be reloaded on application startup if not yet sent. In particular, the emails are loaded when scheduler is constructed.

###Impact of the Persistence layer on the default priority-based scheduler The default scheduler is PriorityQueueEmailSchedulerService, which by default stores everything in memory. Clerarly, having thousands email being scheduled, storing everything in memory could drive to a potential OutOfMemoryException. Enabling the persistence layer should allow to use REDIS for persisting scheduled emails. Anyway, you may want to customize the behavior of the scheduler when interacting with the persistence layer, you can use the following params:

spring.mail.scheduler.persistence.desiredBatchSize=200
spring.mail.scheduler.persistence.minKeptInMemory=100
spring.mail.scheduler.persistence.maxKeptInMemory=1000

The first defines the maximum amount of emails being loaded from the persistence layer when a slot is available in the priority queues; the second amount is the wish for the minimum amount of emails available in memory: the third defines the amount of emails to be kept in memory. Clearly, these two values impact the response time of the scheduler. The less you store in memory, the more it takes to send the next email. The smaller is the batch size, the higher the times you interact with the persistence layer.

Customize email logging

Very often, you want to log the email that you just sent or scheduled, but you would like to avoid a full toString of the given email object. For instance, you may want to anonymize an email address, or to ignore custom headers. Here follows a list of properties you can use with some examples:

spring.mail.logging.enabled=true

spring.mail.logging.strategy.from=PLAIN_TEXT
spring.mail.logging.strategy.replyTo=HIDDEN
spring.mail.logging.strategy.to=FULL_TEXT_FROM_COMMERCIAL_AT,
spring.mail.logging.strategy.cc=HIDDEN
spring.mail.logging.strategy.bcc=HIDDEN
spring.mail.logging.strategy.subject=PLAIN_TEXT
spring.mail.logging.strategy.body=FIRST_DOZEN_THEN_STARS
spring.mail.logging.strategy.attachments=HIDDEN
spring.mail.logging.strategy.encoding=HIDDEN
spring.mail.logging.strategy.locale=HIDDEN
spring.mail.logging.strategy.sentAt=STANDARD_DATE_FORMAT_WITH_ZONE_ID
spring.mail.logging.strategy.receiptTo=HIDDEN
spring.mail.logging.strategy.depositionNotificationTo=HIDDEN
spring.mail.logging.strategy.ignore.customHeaders=true
spring.mail.logging.strategy.ignore.nullAndEmptyCollections=true

Allowed logging strategies are defined in the enum it.ozimov.springboot.mail.logging.LoggingStrategy. Do not pretend to apply a date-only strategy to an email address, or an email address-only strategy to a text field. Usage should be straightforward.

Future plans

See open issues.

Any contribution is welcome (and warmly encouraged).

License

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

How to open an issue

Are you experiencing an issue? Please, post a question on StackOverflow or open an issue on GitHub.

Issues that are not reporting a minimal set of info to reproduce the bug will be closed with no further comments.

Information that should be provided for investigations:

  • version used
  • pom.xml
  • application.properties
  • exception stacktrace
  • Are the provided examples run with success?

==============================================

forthebadge forthebadge forthebadge forthebadge

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].