1

I need to implement the below logic using java.

--> When i click on a button, MS Outlook need to get opened with To,CC,Subject and attachment.

We can use mailto for doing this but we can't add attachment if we use mailto.

i need to add multiple attachment from a shared folder to MS outlook

Please help me.

Using switched it is possible to have single attachment but i need to open outlook with 2+ attachment and send button should be available so that user can send the mail

Thomas
  • 213
  • 5
  • 17

1 Answers1

1

Use JavaMail to create a multipart mime message with your To, CC, Subject and attachment. Then instead of transporting the message call saveChanges and writeTo and store the email to the file system.

There is an undocumented /eml switch that can be used to open the MIME standard format. For example, outlook /eml filename.eml There is a documented /f switch which will open msg files. For example outlook /f filename.msg The x-unsent can be used to toggle the send button.

Here is an example to get you started:

public static void main(String[] args) throws Exception {
    //Create message envelope.
    MimeMessage msg = new MimeMessage((Session) null);
    msg.addFrom(InternetAddress.parse("you@foo.com"));
    msg.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("support@bar.com"));
    msg.setRecipients(Message.RecipientType.CC,
            InternetAddress.parse("manager@baz.com"));
    msg.setSubject("Hello Outlook");
    //msg.setHeader("X-Unsent", "1");

    MimeMultipart mmp = new MimeMultipart();
    MimeBodyPart body = new MimeBodyPart();
    body.setDisposition(MimePart.INLINE);
    body.setContent("This is the body", "text/plain");
    mmp.addBodyPart(body);

    MimeBodyPart att = new MimeBodyPart();
    att.attachFile("c:\\path to file.attachment");
    mmp.addBodyPart(att);

    msg.setContent(mmp);
    msg.saveChanges();


    File resultEmail = File.createTempFile("test", ".eml");
    try (FileOutputStream fs = new FileOutputStream(resultEmail)) {
        msg.writeTo(fs);
        fs.flush();
        fs.getFD().sync();
    }

    System.out.println(resultEmail.getCanonicalPath());

    ProcessBuilder pb = new ProcessBuilder();
    pb.command("cmd.exe", "/C", "start", "outlook.exe",
            "/eml", resultEmail.getCanonicalPath());
    Process p = pb.start();
    try {
        p.waitFor();
    } finally {
        p.getErrorStream().close();
        p.getInputStream().close();
        p.getErrorStream().close();
        p.destroy();
    }
}

You'll have to handle clean up after the email client is closed.

You also have to think about the security implications of email messages being left on the file system.

jmehrens
  • 10,580
  • 1
  • 38
  • 47