Sending attachments with mails
We can also attach various kinds of files to the mail. This functionality is supported by the MimeMessageHelper
class. If you just want to send a MIME message without an attachment, you can opt for MimeMesagePreparator
. If the requirement is to have an attachment to be sent with the mail, we can go for the MimeMessageHelper
class with file APIs.
Spring provides a file class named org.springframework.core.io.FileSystemResource
, which has a parameterized constructor that accepts file objects.
public class SendMailwithAttachment { public static void main(String[] args) throws MessagingException { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class); ctx.refresh(); JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class); MimeMessage mimeMessage = mailSender.createMimeMessage(); //Pass true flag for multipart message MimeMessageHelper mailMsg = new MimeMessageHelper...