Thursday, 11 March 2021

Send email with attachment in spring boot

 https://howtodoinjava.com/spring-boot2/send-email-with-attachment/

public void sendMailWithAttachment(String to, String subject, String bodyTextMsg, String fileToAttach) 

{

System.out.println("file loc------------"+fileToAttach);

    MimeMessagePreparator preparator = new MimeMessagePreparator() 

    {

        public void prepare(MimeMessage mimeMessage) throws Exception 

        {

            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

            mimeMessage.setFrom(new InternetAddress(fromEmailId));

            mimeMessage.setSubject(subject);

            

            Multipart multipartContent= new MimeMultipart();

            MimeBodyPart mimeBodyPart =new MimeBodyPart();

            mimeBodyPart.setText(bodyTextMsg);

            MimeBodyPart mimeBodyPartAttachment =new MimeBodyPart();

            mimeBodyPartAttachment.attachFile(fileToAttach);

            multipartContent.addBodyPart(mimeBodyPart);

            multipartContent.addBodyPart(mimeBodyPartAttachment);

            mimeMessage.setContent(multipartContent,"text/csv; charset=utf-8");

            System.out.println("email send sucessfully");

        }

    };

     

    try {

        mailSender.send(preparator);

        System.out.println("email send sucessfully");

        

    }

    catch (MailException ex) {

        // simply log it and go on...

        System.out.println(ex.getMessage());

    }

}


https://coderanch.com/t/271609/java/Java-Mail-send-Multiple-recipients

No comments:

Post a Comment