简体   繁体   中英

Java send mail automatically with local mail client

From within a java program I want to send a mail via the local mail client of the user automatically.

I use the following code to open up the client and fill in the required fields but how do I send it now automatically without any user interaction?

    private void sendMail() throws MessagingException {
    try {
        Desktop.getDesktop().mail(new URI("mailto:abc@def.com?subject=someSubject&cc=aa@bb.cc,dd@dd.ds&bcc=x@y.zz&body=someBodyText"));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Basically I want to send mails that don't leave the network of the company.

The answer is Java Mail API .

Basically, you need a mail account (usually username+password), you also need the mail SP's SMTP server address, which is usually on their website.

I found a way to deal with outlook at least, following this guide: Vogella, Eclipse-Microsoft Integration

Basically I'm using the OleClientSite class to invoke outlook. Then I'm using the oleAutomation class to send the mail.

Code snippet:

            Shell shell = new Shell(Display.getDefault());
            OleFrame frame = new OleFrame(shell, SWT.NONE);
            // This should start outlook if it is not running yet
            OleClientSite site = new OleClientSite(frame, SWT.NONE, "OVCtl.OVCtl");
            site.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
            // Now get the outlook application
            OleClientSite site2 = new OleClientSite(frame, SWT.NONE,
                "Outlook.Application");
            OleAutomation outlook = new OleAutomation(site2);
            // 
            OleAutomation mail = invoke(outlook, "CreateItem", 0 /* Mail item */)
                .getAutomation();
            setProperty(mail, "To", "aav@gmail.com"); /*
                                   * Empty but could also be
                                   * predefined
                                   */

            setProperty(mail, "Bcc", "test@gmail.com"); /*
                                   * Empty but could also be
                                   * predefined
                                   */

            setProperty(mail, "BodyFormat", 2 /* HTML */);
            setProperty(mail, "Subject", "Top News for you");
            setProperty(mail, "HtmlBody",
                "<html>Hello<p>, please find some infos here.</html>");

            invoke(mail, "Send" /* or "Send" */);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM