0

Here in this it works perfectly fine but instead of using the recieved file I have use file path How can I do that I though converting it into input stream would do some good but there is no constructor with input stream Please let me know Thanks in advance

@RequestMapping("/SendMail")
    public String mail(@RequestParam("prescription") MultipartFile prescription,@RequestParam("email") String email,HttpSession session) {
        try {
            customer ct=custServ.customerExists(email);
            InputStream in = prescription.getInputStream();
            String filename=prescription.getName();
            if(ct!=null){
                final String SEmail="email@gmail.com";
                final String SPass="passowrd";
                final String REmail=email;
                final String Sub="Your prescription is here!";
                //mail send Code
            Properties props=new Properties();
            props.put("mail.smtp.host","smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port","465");
            props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth","true");
            props.put("mail.smtp.port","465");
            Session ses=Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication(SEmail,SPass);
                }
            }
            );
            Message message=new MimeMessage(ses);
            message.setFrom(new InternetAddress(SEmail));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(REmail));
            message.setSubject(Sub);
            
            BodyPart messageBodyPart = new MimeBodyPart();
             messageBodyPart.setText("This is your prescription here");
             Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            messageBodyPart = new MimeBodyPart(); 
            
           // File filep=new File(prescription);
            DataSource source = new FileDataSource("C:\\Users\\Narci\\Desktop\\frontend\\Myqr3.jpg");
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
             message.setContent(multipart);
            
            Transport.send(message);
            session.setAttribute("msg","Mail Sent successfully.");
            }
            else{
                session.setAttribute("msg", "Wrong Emial ID");
            }
            return "Doctor";
        }
        catch(Exception e) {
        e.printStackTrace();
        return "Error";
        }
    } ```

user207421
  • 305,947
  • 44
  • 307
  • 483
  • What exactly are you trying to do? What is the source of input? – Jason Sep 08 '20 at 18:23
  • In a nutshell I want to fetch file from frontend and send mail via code attached with file that I received from frontend – Shivansh Bajpai Sep 08 '20 at 18:45
  • So for clarifying your intentions: do you want to basically attach a file through your front-end and then send it attached to a mail using Gmail API right? What is the issue you encounter when using a [Multipart upload](https://developers.google.com/gmail/api/guides/uploads#multipart)? – Mateo Randwolf Sep 09 '20 at 08:20
  • @MateoRandwolf I need to know what changes can I make in this code so that I don't have to use file path to attach file in this code – Shivansh Bajpai Sep 10 '20 at 07:07
  • So, do you basically want to send an email with Gmail API which has an attachment? And you don't want to write the file path to attach this file to the email content? – Mateo Randwolf Sep 11 '20 at 13:44
  • @MateoRandwolf excatly – Shivansh Bajpai Sep 11 '20 at 20:06
  • Are you Ok then with a solution that just basically takes the file obtained in the frontend with ```input``` of type ```file``` and then converts that file object into a base64 object to then be used by your backend to attach it to your mail? Is that what you wanted? To take the file from the front-end, convert it into an object to then be used in the backend as a simple object so that you dont have to store it as a file in your backend? – Mateo Randwolf Sep 15 '20 at 11:05
  • @MateoRandwolf Yes Yes – Shivansh Bajpai Sep 16 '20 at 17:10

2 Answers2

0

This is kind of a shot in the dark because I don't believe I truly understand the question. If the question is; How can I use a File instead of a MultipartFile and obtain an InputStream then the answer would be to use an existing library like Files.newInputStream with a Path as the parameter.

Path path = Paths.get("path", "to", "my", "file");

try (InputStream input = Files.newInputStream(path)) {

}
Jason
  • 5,154
  • 2
  • 12
  • 22
  • I think it's better to use comments section for the discussion/clarification purposes, when you're not clear about the question. – Giorgi Tsiklauri Sep 08 '20 at 18:29
  • @GiorgiTsiklauri That is a really good point, and I should have sought out more information before answering. My only reasoning for an answer was due to the code provided. Thank you for the insight, I should have likely sought out for information. – Jason Sep 08 '20 at 18:31
0

From this other Stack Overflow answer (this answer is posted as a community wiki) you can get in your front-end the file object and convert it into a base64 object as follows:

const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
});

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   console.log(await toBase64(file));
}

Main();

Then, with this Base64 object you could send it to the backend with a PUT request to then attach it to the email following Gmail API instructions for multipart upload.

halfer
  • 19,824
  • 17
  • 99
  • 186
Mateo Randwolf
  • 2,823
  • 1
  • 6
  • 17