Guide on sending a webpage as an email attachment with Spring Boot, JavaScript, and Ajax

I recently added a feature that allows users to generate invoices in PDF format. There are now two buttons available - one for printing the invoice and another for emailing it. When the user clicks on the email button, the invoice is supposed to be sent to a specific email address.

However, I'm feeling a little unsure about the implementation. If anyone has any suggestions, I would greatly appreciate it!

https://i.sstatic.net/sUNGk.jpg

https://i.sstatic.net/wT9Ha.jpg

Answer №1

@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    public EmailService emailService;


    @RequestMapping(value = {"/send"}, method = RequestMethod.POST)
    public String sendEmailWithAttachment(Model model,
                             HttpServletRequest request) {

             //Implement logic to generate PDF file

            emailService.sendMessageWithAttachment(to, subject, body, pdfFile);

    }

public interface EmailService{

      sendMessageWithAttachment(
          String to, String subject, String text, String pathToAttachment, FileSystemResource pdfFileToSend); 

}

@Component
public class EmailServiceImpl implements EmailService {

  @Autowired
  private JavaMailSender emailSender;

  @Override
  public void sendMessageWithAttachment(
  String to, String subject, String text, String pathToAttachment, FileSystemResource pdfFileToSend) {
    // ...
    
    MimeMessage message = emailSender.createMimeMessage();
     
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    
    helper.setFrom("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d53524f584d51447d5f5c58     515948535a135e5250">[email protected]</a>");
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(text);
    
    helper.addAttachment("PDF File Attachment", pdfFileToSend);

    emailSender.send(message);
    // ...
}

Your front-end code will call the /mail/send endpoint, which triggers the generation of a PDF for the user, creates an email and sends it using spring-boot-mail-starter

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

References:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The uploaded file size exceeds the allowed limit in jquery-file-upload

I'm currently utilizing the jquery-file-upload plugin for file uploads. Within this process, I have a bind to the add callback in order to gather the files for uploading. Upon form submission, I trigger the 'send' command to initiate the upl ...

What is causing the sorting table to fail in React when using useState?

import React, { useState } from "react"; import "./App.css"; const App = () => { const [data, setData] = useState([ { rank: 1, name: "John", age: 29, job: "Web developer", }, { rank: 2, name: "Micha ...

Only the first element is responding to the button onclick event

When I click the button on the elements, the overlay box only works with the first one and not the rest. I have already tried adding two classes but it doesn't seem to be working. I read that this might be the issue, but I am struggling to make it wo ...

Create an instance of an object in order to make it accessible to several directives

My Current Project: I am currently working on developing two attribute directives. One directive is designed to move an element to the left, while the other centers an element on the page. Below is a snippet of the code showcasing how I am using ng-style t ...

Is there a way for me to iterate through an array of objects within a Redux reducer file in order to remove a specific user?

I am facing a challenge while trying to remove a user in redux. The issue arises when I use the map function in the reducer.js file and encounter a 'state.users.map is not a function' error. Upon investigation, I realized that the array consists ...

Issue with Spring JPA: Foreign keys missing from response

I have a database containing entities in a parent-child relationship. When querying the child table to retrieve all rows, only the non-foreign key fields are returned in the JSON response. Can someone assist me in including the foreign key in the JSON resp ...

Issues with merging styles in TinyMCE 4

I've exhausted all the current configuration options and I'm still unable to resolve this issue. My goal is to have the style tag appended to the selected element without generating an additional span. For example: <p>Hello World!</p> ...

Tips on utilizing webui-popover for hover interactions and loading content dynamically using AJAX

I recently came across an interesting popover feature from https://github.com/sandywalker/webui-popover. I am trying to implement a popover function similar to 'quora': where the link is clickable, but hovering over it displays a popover with dyn ...

Why is my React Native component not getting the props it needs?

Transitioning from my experience with React, I initially believed that passing props worked the same way, but it turns out that's not the case? Currently, I am working on a login form where I want to differentiate between the styling of the sign in a ...

Fix a carousel layout problem

I've made changes to an HTML-PHP module to display portfolio images as a carousel, and I'm using the same module on this website too. However, I've encountered an issue with duplicate content and the previous-next navigation buttons. Can so ...

Matching a string with a variable in JavaScript: A simple guide

Can you assist me? I am trying to have activeLayers = [bus,stops,slot1] instead of activeLayers = ["bus","stops","slot1"]. How can I achieve this? Essentially, I want to convert the string into the object it references. Unfortunately, my current approach ...

Show the page information directly on the current page instead of redirecting it to a different page

On my website (For example, Link1: http://localhost:8086/MyStrutsApp/login.do), there are multiple links available. Whenever a user clicks on one of these links, they are directed to another page (For instance, link2: http://localhost:8086/MyStrutsApp/AddB ...

Discover the outcome of two asynchronous ajax requests using XHR's onprogress event-handler

My current challenge involves seeking out images within an ajax request response and extracting the src URL for utilization in another ajax request. I am aiming to monitor the loading progress of each image and display the resulting progress in a designat ...

Starting from index 1, I am crafting a JSON array

I am trying to generate a JSON array that starts with index 1 Below is the code I am using to extract images from websites: $image_urls = array(); //retrieve all image URLs from the content foreach($get_content->find(&ap ...

Utilize AJAX to securely transmit solely $_POST variables to PHP, omitting any HTML responses

Seeking to solely transfer $_POST's variables (variables from the $_POST array) into a PHP file via AJAX call without displaying any success messages like alert('ok, it's fine') or $('blah').text('done it!'). My goal ...

Conversation taking place outside of an iframe

Having a slight issue with a JavaScript dialog. There's a button and a dialog inside an iframe with the following code: $( "#correcto" ).dialog({ width: 600, closeOnEscape: true, autoOpen: false, draggable: false, modal: true, ...

What is the best way to retrieve the value of this event in a React component?

Is there a way to retrieve the value of an input field? Typically, I would use event.target.value to do so. However, in this case, that method is not viable because the path of event.target leads me to an li element instead: https://i.sstatic.net/0iB9v.pn ...

Tips for maintaining efficiency in an Ajax web form solution

Currently, our solution involves using Web forms ASP.Net 4.0. We utilize web methods and services in various ways, such as calling them through standard web forms or directly with jQuery ajax posts and gets to reduce the footprint. We are seeking to enhan ...

Searching for data in MongoDB with multiple conditions using the Mongoose find

When I attempt to verify a verification code during user registration, the query has multiple conditions. If a document is returned, then the verification code is considered verified; otherwise, it is not. The issue with the following snippet is that it ...