在Spring Boot中的电子邮件中添加多部分文件作为附件

发布于 2025-01-28 08:28:28 字数 2820 浏览 1 评论 0原文

我想通过PDF附件发送来自Spring Boot的电子邮件。我从发布通话中收到了PDF文件作为多部分文件。

这是到目前为止的控制器类(sendemails方法 emailservice service):

@PostMapping("/email")
    public ResponseEntity<?> sendEmail(@RequestParam("file") MultipartFile pdfFile,
                                       @RequestParam("email") String email) {


        boolean result = this.emailService.sendEmails(email, pdfFile);
        
        if (result) {
            return ResponseEntity.ok("Email sent...");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Email sending failed");
        }
    }

现在是sendemails方法:

public boolean sendEmails(String reciever, MultipartFile pdf) {

        try {
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
            mailSender.setHost("smtp.gmail.com");
            mailSender.setPort(Integer.parseInt(Objects.requireNonNull("587")));
            mailSender.setUsername("~my email~");
            mailSender.setPassword("~my pw~");

            Properties javaMailProperties = new Properties();
            javaMailProperties.put("mail.smtp.starttls.enable", "true");
            javaMailProperties.put("mail.smtp.auth", "true");
            javaMailProperties.put("mail.transport.protocol", "smtp");
            javaMailProperties.put("mail.debug", "true");
            javaMailProperties.put("mail.smtp.ssl.trust", "smtp.gmail.com");

            mailSender.setJavaMailProperties(javaMailProperties);

            sendEmailAndUpdate(reciever, pdf, mailSender);

            System.out.println("Email Sent  Successfully...");

        } catch (Exception e) {
            System.out.println("EmailService File Error" + e);
            return false;
        }
        return true;

    }

现在,在sendemailandupdate我有接收器的电子邮件地址,PDF(作为多片file)和Javamailsender。到目前为止,这是此方法:

private void sendEmailAndUpdate(String recieverEmail, MultipartFile file, JavaMailSender mailSender) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

            mimeMessageHelper.setSubject("PDF email");
            mimeMessageHelper.setFrom(~My Email~);
            mimeMessageHelper.setTo(recieverEmail);
            
            mimeMessageHelper.setText("This is email body");

            // Code for attaching the PDF goes here

            mailSender.send(mimeMessageHelper.getMimeMessage());

        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

在这里,我想将PDF文件(我作为多Attrantfile)附加到电子邮件。这可能是一个菜鸟问题,我可能会缺少明显的东西,但是我是新手,我在网上找不到有关如何做到这一点的资源。谁能将我链接到这种资源或提供解决方案?先感谢您。

I want to send an email from Spring Boot with a pdf attachment. I have received the pdf file as a multipart file from a POST call.

Here's my controller class so far (sendEmails method is included in emailService service):

@PostMapping("/email")
    public ResponseEntity<?> sendEmail(@RequestParam("file") MultipartFile pdfFile,
                                       @RequestParam("email") String email) {


        boolean result = this.emailService.sendEmails(email, pdfFile);
        
        if (result) {
            return ResponseEntity.ok("Email sent...");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Email sending failed");
        }
    }

And here's sendEmails method:

public boolean sendEmails(String reciever, MultipartFile pdf) {

        try {
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
            mailSender.setHost("smtp.gmail.com");
            mailSender.setPort(Integer.parseInt(Objects.requireNonNull("587")));
            mailSender.setUsername("~my email~");
            mailSender.setPassword("~my pw~");

            Properties javaMailProperties = new Properties();
            javaMailProperties.put("mail.smtp.starttls.enable", "true");
            javaMailProperties.put("mail.smtp.auth", "true");
            javaMailProperties.put("mail.transport.protocol", "smtp");
            javaMailProperties.put("mail.debug", "true");
            javaMailProperties.put("mail.smtp.ssl.trust", "smtp.gmail.com");

            mailSender.setJavaMailProperties(javaMailProperties);

            sendEmailAndUpdate(reciever, pdf, mailSender);

            System.out.println("Email Sent  Successfully...");

        } catch (Exception e) {
            System.out.println("EmailService File Error" + e);
            return false;
        }
        return true;

    }

Now, in the sendEmailAndUpdate method I have the reciever's email address, the pdf (as a MultipartFile), and the JavaMailSender. Here's this method so far:

private void sendEmailAndUpdate(String recieverEmail, MultipartFile file, JavaMailSender mailSender) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

            mimeMessageHelper.setSubject("PDF email");
            mimeMessageHelper.setFrom(~My Email~);
            mimeMessageHelper.setTo(recieverEmail);
            
            mimeMessageHelper.setText("This is email body");

            // Code for attaching the PDF goes here

            mailSender.send(mimeMessageHelper.getMimeMessage());

        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

Here I want to attach the pdf file (which I have as a MultipartFile) to the email. This might be a noob question and I might be missing something obvious, but I'm new to this and I couldn't find any resources online on how to do this. Can anyone link me to such resource or provide with a solution? Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

平生欢 2025-02-04 08:28:28

您可以直接连接

 mimeMessageHelper.addAttachment("fileName", file);

MultipartFile已经扩展了InputStreamSource的类

 public interface MultipartFile extends InputStreamSource {

You can attached directly

 mimeMessageHelper.addAttachment("fileName", file);

MultipartFile already extend class of InputStreamSource

 public interface MultipartFile extends InputStreamSource {
冷月断魂刀 2025-02-04 08:28:28

通过使用多片文件文件作为模型类的一部分,也将起作用。

package com.techgeeknext.request;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class NotificationEmail {
    private String to;
    private String cc;
    private String subject;
    private String bodyMsg;
    private MultipartFile file;
    private boolean isHtmlMsg;
}

在控制器类中使用Modelattribute的Post方法。

package com.techgeeknext.controller;

import com.techgeeknext.request.NotificationEmail;
import com.techgeeknext.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class NotificationController {

    @Autowired
    NotificationService notificationService;

    @PostMapping("/sendNotificationEmail")
    public ResponseEntity<String> sendNotificationEmail(@ModelAttribute NotificationEmail notificationEmail) {
        boolean emailSent = false;
        if (notificationEmail.getFile()!=null) {
            emailSent = notificationService.sendNotificationEmailWithAttachment(notificationEmail, notificationEmail.getFile());
        } else {
            emailSent = notificationService.sendTextNotificationEmail(notificationEmail);
        }
        if (emailSent) {
            return ResponseEntity.ok("Email sent.");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error occurred while sending email.");
        }
    }
}

示例 详细说明上述实现。

By using MultipartFile file as part of the model class will also work.

package com.techgeeknext.request;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class NotificationEmail {
    private String to;
    private String cc;
    private String subject;
    private String bodyMsg;
    private MultipartFile file;
    private boolean isHtmlMsg;
}

And in Controller class use post method with ModelAttribute.

package com.techgeeknext.controller;

import com.techgeeknext.request.NotificationEmail;
import com.techgeeknext.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class NotificationController {

    @Autowired
    NotificationService notificationService;

    @PostMapping("/sendNotificationEmail")
    public ResponseEntity<String> sendNotificationEmail(@ModelAttribute NotificationEmail notificationEmail) {
        boolean emailSent = false;
        if (notificationEmail.getFile()!=null) {
            emailSent = notificationService.sendNotificationEmailWithAttachment(notificationEmail, notificationEmail.getFile());
        } else {
            emailSent = notificationService.sendTextNotificationEmail(notificationEmail);
        }
        if (emailSent) {
            return ResponseEntity.ok("Email sent.");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error occurred while sending email.");
        }
    }
}

This Example explain above implementation in detail.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文