How to Send Email In Spring Boot?

17 minutes read

To send email in Spring Boot, you can follow these simple steps:

  1. Ensure that you have the necessary dependencies included in your project's pom.xml file. These dependencies usually include the 'spring-boot-starter-mail' and 'javax.activation' libraries.
  2. Configure the email settings in your application.properties or application.yml file. Include the SMTP server details such as host, port, username, and password. For example: spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=user@example.com spring.mail.password=password
  3. Create a Java class to handle the email sending functionality. This class can be annotated with @Service or any other relevant Spring stereotype annotation. Autowire the JavaMailSender bean to get access to the pre-configured email properties. @Service public class EmailService { @Autowired private JavaMailSender emailSender; public void sendEmail(String to, String subject, String text) { MimeMessage message = emailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); emailSender.send(message); } catch (MessagingException e) { e.printStackTrace(); } } }
  4. Use the created EmailService class in your application wherever you want to send an email. Inject the EmailService bean and call the sendEmail() method with the recipient's email address, subject, and email body. @Autowired private EmailService emailService; // Example usage in a controller method @PostMapping("/sendemail") public void sendEmails() { String to = "recipient@example.com"; String subject = "Test Email"; String body = "This is a test email sent using Spring Boot!"; emailService.sendEmail(to, subject, body); }


By following these steps, you should be able to send emails using Spring Boot.

Best Spring Boot Books to Read in April 2024

1
Full Stack Development with Spring Boot and React: Build modern and scalable web applications using the power of Java and React, 3rd Edition

Rating is 5 out of 5

Full Stack Development with Spring Boot and React: Build modern and scalable web applications using the power of Java and React, 3rd Edition

2
Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications

Rating is 4.9 out of 5

Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications

3
Spring Boot in Action

Rating is 4.8 out of 5

Spring Boot in Action

4
Spring Boot: Up and Running: Building Cloud Native Java and Kotlin Applications

Rating is 4.7 out of 5

Spring Boot: Up and Running: Building Cloud Native Java and Kotlin Applications

5
Learning Spring Boot 3.0: Simplify the development of production-grade applications using Java and Spring, 3rd Edition

Rating is 4.6 out of 5

Learning Spring Boot 3.0: Simplify the development of production-grade applications using Java and Spring, 3rd Edition

6
Spring in Action, Sixth Edition

Rating is 4.5 out of 5

Spring in Action, Sixth Edition

7
Modern API Development with Spring and Spring Boot: Design highly scalable and maintainable APIs with REST, gRPC, GraphQL, and the reactive paradigm

Rating is 4.4 out of 5

Modern API Development with Spring and Spring Boot: Design highly scalable and maintainable APIs with REST, gRPC, GraphQL, and the reactive paradigm

8
Spring Boot and Angular: Hands-on full stack web development with Java, Spring, and Angular

Rating is 4.3 out of 5

Spring Boot and Angular: Hands-on full stack web development with Java, Spring, and Angular


What is Spring Boot?

Spring Boot is an open-source Java-based framework used for building stand-alone and production-ready applications. It is a part of the Spring Framework, designed to simplify the process of setting up and configuring Spring applications. Spring Boot offers several features like auto-configuration, embedded servers, production-ready monitoring, and simplified dependency management. It aims to provide a quick and efficient way to develop robust and scalable Spring applications with minimal configuration, allowing developers to focus more on writing code rather than setting up infrastructure.


How to send emails with different character encodings in Spring Boot?

To send emails with different character encodings in Spring Boot, follow these steps:

  1. Set the spring.mail.default-encoding property in the application.properties file to specify the default character encoding for emails. For example: spring.mail.default-encoding=UTF-8
  2. Autowire the JavaMailSender class into your service or controller. For example: @Autowired private JavaMailSender javaMailSender;
  3. Create a MimeMessage object using the JavaMailSender instance: MimeMessage message = javaMailSender.createMimeMessage();
  4. Set the sender, recipient, subject, and content of the email: message.setFrom(new InternetAddress("sender@example.com")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com")); message.setSubject("Email Subject"); message.setText("Email Content");
  5. Set the character encoding for the message using the MimeMessageHelper class: MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); helper.setText("Email Content", true); Note: The third argument of the MimeMessageHelper constructor specifies the character encoding.
  6. Send the message using the JavaMailSender instance: javaMailSender.send(message);


By following these steps, you can send emails with different character encodings in Spring Boot.


How to send an email with attachments in Spring Boot?

To send an email with attachments in Spring Boot, you can use the JavaMailSender API. Here's an example of how you can accomplish this:

  1. Add the needed dependencies to your pom.xml file:
1
2
3
4
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>


  1. Configure the mail properties in your application.properties file:
1
2
3
4
5
6
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true


  1. Create a service or method to send the email:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class EmailService {

   @Autowired
   private JavaMailSender javaMailSender;

   public void sendEmailWithAttachment(String to, String subject, String body, String attachmentPath) throws MessagingException {
       MimeMessage message = javaMailSender.createMimeMessage();
       MimeMessageHelper helper = new MimeMessageHelper(message, true);

       helper.setTo(to);
       helper.setSubject(subject);
       helper.setText(body);

       FileSystemResource file = new FileSystemResource(new File(attachmentPath));
       helper.addAttachment(file.getFilename(), file);

       javaMailSender.send(message);
   }
}


  1. Use the EmailService class to send an email with an attachment:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;

@RestController
public class EmailController {

   @Autowired
   private EmailService emailService;

   @PostMapping("/send-email")
   public String sendEmailWithAttachment(@RequestParam String to,
                                         @RequestParam String subject,
                                         @RequestParam String body,
                                         @RequestParam String attachmentPath) {
       try {
           emailService.sendEmailWithAttachment(to, subject, body, attachmentPath);
           return "Email sent successfully!";
       } catch (MessagingException e) {
           e.printStackTrace();
           return "Failed to send email!";
       }
   }
}


In this example, the sendEmailWithAttachment method takes the recipient email address, subject, body, and attachment path as parameters and uses the JavaMailSender to send the email with attachment.

Best Cloud Providers to Host Java Spring Boot in 2024

1
AWS

Rating is 5 out of 5

AWS

2
DigitalOcean

Rating is 4.9 out of 5

DigitalOcean

3
Vultr

Rating is 4.8 out of 5

Vultr

4
Cloudways

Rating is 4.7 out of 5

Cloudways


How to handle email subscription/unsubscription in Spring Boot?

To handle email subscription/unsubscription in a Spring Boot application, you can follow these steps:

  1. Define the EmailSubscriber entity: Create a class that represents an email subscriber. This class can have properties such as email address, subscription status, and other relevant information.
  2. Create the EmailSubscriber repository: Use Spring Data JPA to create a repository interface for the EmailSubscriber entity. This interface will provide methods to perform CRUD operations on the email subscribers.
  3. Create the email subscription/unsubscription endpoints: Define the necessary endpoints in your Spring Boot application for email subscription and unsubscription. For example, you can use the following REST endpoints: POST /subscribe: This endpoint will receive an email address and save it as a subscribed email subscriber in the database. POST /unsubscribe: This endpoint will receive an email address and mark it as unsubscribed in the database.
  4. Implement the email subscription/unsubscription logic: In the respective controller methods for subscription and unsubscription, you can use the EmailSubscriber repository to save or update the subscriber's status in the database.
  5. Implement the email sending functionality: You can use any Java email library (e.g., JavaMail, Apache Commons Email) to send subscription and unsubscription confirmation emails to the subscribers.
  6. Add validation and error handling: Validate the email address format before saving it to the database. Also, handle any exceptions that may occur during the email sending process.
  7. Secure the subscription/unsubscription endpoints: To prevent unauthorized access, you can add authentication and authorization features to these endpoints. For example, you can use Spring Security to secure the endpoints and require users to be logged in or have certain roles.


By following these steps, you can implement email subscription and unsubscription functionality in your Spring Boot application.


How to customize the email sender name and address in Spring Boot?

To customize the email sender name and address in a Spring Boot application, you can do the following:

  1. Open the application.properties file in the src/main/resources directory.
  2. Add the following properties to configure the email sender name and address:
1
2
spring.mail.properties.mail.smtp.from=<sender-email-address>
spring.mail.properties.mail.smtp.fromName=<sender-name>


Replace <sender-email-address> with the email address you want to use as the sender, and <sender-name> with the name you want to appear as the sender.

  1. Restart your Spring Boot application.


After making these changes, the configured email sender name and address will be used when sending emails using JavaMail in your Spring Boot application.


How to send encrypted emails in Spring Boot?

To send encrypted emails in Spring Boot, you can follow these steps:

  1. Add necessary dependencies: Add the following dependencies in your pom.xml file:
1
2
3
4
5
6
7
8
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-crypto</artifactId>
</dependency>


  1. Configure email properties: Open the application.properties or application.yml file and specify the email configuration settings:
1
2
3
4
5
6
spring.mail.host=your_mail_host
spring.mail.port=your_mail_port
spring.mail.username=your_email_username
spring.mail.password=your_email_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true


  1. Create a JavaMailSender bean: In your main application class, create a JavaMailSender bean and autowire it:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
@SpringBootApplication
public class YourApplication {

    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }

    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("your_mail_host");
        mailSender.setPort(your_mail_port);
        mailSender.setUsername("your_email_username");
        mailSender.setPassword("your_email_password");

        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        return mailSender;
    }
}


  1. Create a service to send encrypted emails: Create a service class with a method to send encrypted emails. This method should utilize MimeMessageHelper to send the email securely. Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@Service
public class EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendEncryptedEmail(String recipient, String subject, String body) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setTo(recipient);
        helper.setSubject(subject);
        helper.setText(body);

        // Enable encryption
        helper.getMimeMessage().setContent(createMultipartWithEncryption(body));

        javaMailSender.send(message);
    }

    private Multipart createMultipartWithEncryption(String plainText) throws MessagingException {
        SMIMEEnvelopedGenerator envelopedGenerator = new SMIMEEnvelopedGenerator();
        JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC);

        JcaX509CertificateHolder jcaX509CertificateHolder = new JcaX509CertificateHolder(recipientCertificate);

        envelopedGenerator.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(jcaX509CertificateHolder).setProvider(BouncyCastleProvider.PROVIDER_NAME));

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(plainText);
        messageBodyPart.addHeader("Content-Type", "text/plain; charset=UTF-8");
        messageBodyPart.addHeader("Content-Transfer-Encoding", "quoted-printable");

        MimeBodyPart encryptedPart = SMIMEUtil.toMultipartText(new SMIMEEncrypted(jceCMSContentEncryptorBuilder.build(), envelopedGenerator.generate(new CMSProcessableBodyPart(messageBodyPart))).getContent(), "7bit");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(encryptedPart);

        return multipart;
    }
}


In the createMultipartWithEncryption method, you can modify the encryption algorithm and recipient certificate as per your requirements.

  1. Use the service to send an encrypted email: In your application logic, use the EmailService to send an encrypted email:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@Service
public class YourService {

    @Autowired
    private EmailService emailService;

    public void sendEncryptedEmail() {
        String recipient = "recipient@example.com";
        String subject = "Encrypted Email";
        String body = "This email is encrypted.";

        try {
            emailService.sendEncryptedEmail(recipient, subject, body);
            System.out.println("Encrypted email sent successfully.");
        } catch (MessagingException ex) {
            System.out.println("Failed to send encrypted email. Error: " + ex.getMessage());
        }
    }
}


That's it! Now you can send encrypted emails in Spring Boot using the JavaMailSender and MimeMessageHelper classes along with encryption techniques provided by the Bouncy Castle library.


How to add inline images in email content in Spring Boot?

To add inline images in email content in Spring Boot, you can follow these steps:

  1. Add the spring-boot-starter-mail dependency in your project's pom.xml file:
1
2
3
4
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>


  1. Configure the email properties in the application.properties file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# SMTP Server
spring.mail.host=your-smtp-host
spring.mail.port=your-smtp-port

# Authentication
spring.mail.username=your-username
spring.mail.password=your-password

# TLS/SSL
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true


You can customize the properties based on your mail configuration.

  1. Create a class to handle the email sending logic, for example, EmailService.java:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Base64;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    public void sendEmailWithInlineImage(String toEmail, String subject, String content, byte[] imageBytes, String imageType) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(fromEmail);
        helper.setTo(toEmail);
        helper.setSubject(subject);

        helper.setText(content, true);

        // Add inline image
        helper.addInline("image", new ByteArrayResource(Base64.getEncoder().encode(imageBytes)), imageType);

        javaMailSender.send(message);
    }
}


In this example, the sendEmailWithInlineImage method is responsible for sending the email with an inline image. The imageBytes parameter represents the image content in byte array format, and the imageType parameter represents the image file type (e.g., image/png, image/jpeg, etc.).

  1. You can then use the EmailService class in your desired Spring Boot component to send emails with inline images:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.mail.MessagingException;

@SpringBootApplication
public class YourSpringBootApplication {

    @Autowired
    private EmailService emailService;

    public static void main(String[] args) {
        SpringApplication.run(YourSpringBootApplication.class, args);
    }

    public void sendEmailWithInlineImage() {
        String toEmail = "recipient@example.com";
        String subject = "Email with Inline Image";
        String content = "<html><body><h1>Hello!</h1><img src='cid:image'></body></html>";  // Placeholder "cid:image" will be replaced with the actual inline image

        byte[] imageBytes = getImageBytes();  // Replace this with your own logic to get the image content in byte array format
        String imageType = "image/png";  // Replace this with your own image file type

        try {
            emailService.sendEmailWithInlineImage(toEmail, subject, content, imageBytes, imageType);
            System.out.println("Email sent successfully!");
        } catch (MessagingException e) {
            System.err.println("Failed to send email: " + e.getMessage());
        }
    }

    // Other methods...

}


In this example, the sendEmailWithInlineImage method demonstrates how to use the EmailService class to send an email with an inline image. Replace the toEmail, subject, content, getImageBytes(), and imageType values as per your requirement.


Note: Ensure that the getImageBytes() method retrieves the image content in byte array format from your desired source, such as a file or database, depending on your implementation.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To integrate Spring Boot with Angular, the following steps can be followed:Create a new Spring Boot project: Start by setting up a new Spring Boot project using your preferred IDE or Spring Initializer. Include the necessary dependencies for web and data. Set ...
To connect Spring Boot to MySQL, you need to follow these steps:First, make sure you have MySQL installed and running on your system. In your Spring Boot project, open the application.properties file. Add the following properties to the file: spring.datasourc...
To send an email using PHP, you can use the built-in mail() function. Here is the basic syntax and steps to send an email:Set up the necessary variables for the email headers and content: $to = &#34;recipient@example.com&#34;; // Email address of the recipient...