Example usage for java.awt Desktop mail

List of usage examples for java.awt Desktop mail

Introduction

In this page you can find the example usage for java.awt Desktop mail.

Prototype

public void mail(URI mailtoURI) throws IOException 

Source Link

Document

Launches the mail composing window of the user default mail client, filling the message fields specified by a mailto: URI.

Usage

From source file:Main.java

public static void main(String[] a) throws URISyntaxException {
    try {//from w w w  .j  a  v  a  2  s . c  om
        Desktop desktop = null;
        if (Desktop.isDesktopSupported()) {
            desktop = Desktop.getDesktop();
        }

        desktop.mail(new URI("name@address.net"));
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

}

From source file:net.sf.jabref.gui.worker.SendAsEMailAction.java

@Override
public void run() {
    if (!Desktop.isDesktopSupported()) {
        message = Localization.lang("Error creating email");
        return;/*from   w w w  .  j ava 2 s .c  om*/
    }

    BasePanel panel = frame.getCurrentBasePanel();
    if (panel == null) {
        return;
    }
    if (panel.getSelectedEntries().isEmpty()) {
        message = Localization.lang("This operation requires one or more entries to be selected.");
        return;
    }

    StringWriter sw = new StringWriter();
    List<BibEntry> bes = panel.getSelectedEntries();

    // write the entries using sw, which is used later to form the email content
    BibEntryWriter bibtexEntryWriter = new BibEntryWriter(
            new LatexFieldFormatter(LatexFieldFormatterPreferences.fromPreferences(Globals.prefs)), true);

    for (BibEntry entry : bes) {
        try {
            bibtexEntryWriter.write(entry, sw, panel.getBibDatabaseContext().getMode());
        } catch (IOException e) {
            LOGGER.warn("Problem creating BibTeX file for mailing.", e);
        }
    }

    List<String> attachments = new ArrayList<>();

    // open folders is needed to indirectly support email programs, which cannot handle
    //   the unofficial "mailto:attachment" property
    boolean openFolders = JabRefPreferences.getInstance()
            .getBoolean(JabRefPreferences.OPEN_FOLDERS_OF_ATTACHED_FILES);

    List<File> fileList = FileUtil.getListOfLinkedFiles(bes,
            frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory());
    for (File f : fileList) {
        attachments.add(f.getPath());
        if (openFolders) {
            try {
                JabRefDesktop.openFolderAndSelectFile(f.getAbsolutePath());
            } catch (IOException e) {
                LOGGER.debug("Cannot open file", e);
            }
        }
    }

    String mailTo = "?Body=".concat(sw.getBuffer().toString());
    mailTo = mailTo.concat("&Subject=");
    mailTo = mailTo.concat(JabRefPreferences.getInstance().get(JabRefPreferences.EMAIL_SUBJECT));
    for (String path : attachments) {
        mailTo = mailTo.concat("&Attachment=\"").concat(path);
        mailTo = mailTo.concat("\"");
    }

    URI uriMailTo;
    try {
        uriMailTo = new URI("mailto", mailTo, null);
    } catch (URISyntaxException e1) {
        message = Localization.lang("Error creating email");
        LOGGER.warn(message, e1);
        return;
    }

    Desktop desktop = Desktop.getDesktop();
    try {
        desktop.mail(uriMailTo);
    } catch (IOException e) {
        message = Localization.lang("Error creating email");
        LOGGER.warn(message, e);
        return;
    }

    message = String.format("%s: %d", Localization.lang("Entries added to an email"), bes.size());
}

From source file:emailplugin.MailCreator.java

private void mail(final Frame parent, final String content, final String title) {
    // Java 6 desktop API
    boolean sent = false;
    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        try {//from w  ww. ja va 2  s.c o  m
            URI uriMailTo = new URI("mailto", "?body=" + content + "&subject=" + title, null);
            desktop.mail(uriMailTo);
            sent = true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (sent) {
        return;
    }

    // fall back to non Java 6 code
    try {
        final String mailTo = "mailto:?body=" + encodeString(content) + "&subject=" + encodeString(title);
        String application;
        String execparam;

        if ((OperatingSystem.isMacOs() || OperatingSystem.isWindows())
                && mSettings.getUseDefaultApplication()) {

            if (OperatingSystem.isMacOs()) {
                application = "/usr/bin/open";
                execparam = mailTo;
            } else {
                application = "rundll32.exe";
                execparam = "url.dll,FileProtocolHandler " + mailTo;
            }

        } else if (StringUtils.isBlank(mSettings.getApplication())) {
            if (OperatingSystem.isOther()) {
                if (!showKdeGnomeDialog(parent)) {
                    return;
                }
                application = mSettings.getApplication();
                execparam = getContentParameter(content);
            } else {
                showNotConfiguredCorrectly(parent);
                return;
            }
        } else {
            application = mSettings.getApplication();
            execparam = getContentParameter(content);
        }

        new ExecutionHandler(execparam, application).execute();

        if (mSettings.getShowEmailOpened()) {
            showEMailOpenedDialog(parent);
        }

    } catch (Exception e) {
        e.printStackTrace();
        int ret = ErrorHandler.handle(
                mLocalizer.msg("ErrorWhileStarting", "Error while starting mail application"), e,
                ErrorHandler.SHOW_YES_NO);

        if (ret == ErrorHandler.YES_PRESSED) {
            MainFrame.getInstance().showSettingsDialog(mPlugin);
        }
    }
}

From source file:com.ssn.event.controller.SSNShareController.java

@Override
public void mouseClicked(MouseEvent e) {
    Object mouseEventObj = e.getSource();
    if (mouseEventObj != null && mouseEventObj instanceof JLabel) {
        JLabel label = (JLabel) mouseEventObj;
        getShareForm().setCursor(new Cursor(Cursor.WAIT_CURSOR));
        // Tracking this sharing event in Google Analytics
        GoogleAnalyticsUtil.track(SSNConstants.SSN_APP_EVENT_SHARING);
        Thread thread = null;/*w w  w . j a va 2 s . c o  m*/
        switch (label.getName()) {
        case "FacebookSharing":
            thread = new Thread() {
                boolean isAlreadyLoggedIn = false;

                @Override
                public void run() {

                    Set<String> sharedFileList = getFiles();
                    AccessGrant facebookAccessGrant = getHomeModel().getHomeForm().getFacebookAccessGrant();
                    if (facebookAccessGrant == null) {
                        try {
                            LoginWithFacebook loginWithFacebook = new LoginWithFacebook(null);
                            loginWithFacebook.setHomeForm(getHomeModel().getHomeForm());
                            loginWithFacebook.login();

                            boolean processFurther = false;
                            while (!processFurther) {
                                facebookAccessGrant = getHomeModel().getHomeForm().getFacebookAccessGrant();
                                if (facebookAccessGrant == null) {
                                    Thread.sleep(10000);
                                } else {
                                    processFurther = true;
                                    isAlreadyLoggedIn = true;
                                }
                            }
                        } catch (InterruptedException ex) {
                            logger.error(ex);
                        }
                    }

                    FacebookConnectionFactory connectionFactory = new FacebookConnectionFactory(
                            SSNConstants.SSN_FACEBOOK_API_KEY, SSNConstants.SSN_FACEBOOK_SECRET_KEY);
                    Connection<Facebook> connection = connectionFactory.createConnection(facebookAccessGrant);
                    Facebook facebook = connection.getApi();
                    MediaOperations mediaOperations = facebook.mediaOperations();

                    if (!isAlreadyLoggedIn) {
                        // SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                        SSNConfirmationDialogBox confirmeDialog = new SSNConfirmationDialogBox();
                        FacebookProfile userProfile = facebook.userOperations().getUserProfile();
                        String userName = "";
                        if (userProfile != null) {
                            userName = userProfile.getName() != null ? userProfile.getName()
                                    : userProfile.getFirstName();
                        }
                        confirmeDialog.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(),
                                "Confirmation", "",
                                "You are already logged in with " + userName + ", Click OK to continue.");
                        int result = confirmeDialog.getResult();
                        if (result == JOptionPane.YES_OPTION) {
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                                    messageDialogBox.initDialogBoxUI(
                                            SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                                            "Successfully uploaded.");
                                    messageDialogBox.setFocusable(true);

                                }
                            });
                        } else if (result == JOptionPane.NO_OPTION) {

                            AccessGrant facebookAccessGrant1 = null;
                            if (facebookAccessGrant1 == null) {
                                try {
                                    LoginWithFacebook loginWithFacebook = new LoginWithFacebook(null);
                                    loginWithFacebook.setHomeForm(getHomeModel().getHomeForm());
                                    loginWithFacebook.login();

                                    boolean processFurther = false;
                                    while (!processFurther) {
                                        facebookAccessGrant1 = getHomeModel().getHomeForm()
                                                .getFacebookAccessGrant();
                                        if (facebookAccessGrant1 == null) {
                                            Thread.sleep(10000);
                                        } else {
                                            processFurther = true;
                                            //isAlreadyLoggedIn = true;
                                        }
                                    }
                                    connectionFactory = new FacebookConnectionFactory(
                                            SSNConstants.SSN_FACEBOOK_API_KEY,
                                            SSNConstants.SSN_FACEBOOK_SECRET_KEY);
                                    connection = connectionFactory.createConnection(facebookAccessGrant);
                                    facebook = connection.getApi();
                                    mediaOperations = facebook.mediaOperations();
                                } catch (InterruptedException ex) {
                                    logger.error(ex);
                                }
                            }
                        }
                    }

                    String[] videoSupported = SSNConstants.SSN_VIDEO_FORMAT_SUPPORTED;
                    final List<String> videoSupportedList = Arrays.asList(videoSupported);

                    for (String file : sharedFileList) {
                        String fileExtension = file.substring(file.lastIndexOf(".") + 1, file.length());
                        Resource resource = new FileSystemResource(file);

                        if (!videoSupportedList.contains(fileExtension.toUpperCase())) {
                            String output = mediaOperations.postPhoto(resource);
                        } else {
                            String output = mediaOperations.postVideo(resource);
                        }

                    }

                    getShareForm().dispose();
                }
            };
            thread.start();
            break;
        case "TwitterSharing":
            LoginWithTwitter.deniedPermission = false;
            thread = new Thread() {
                boolean isAlreadyLoggedIn = false;

                @Override
                public void run() {
                    Set<String> sharedFileList = getFiles();
                    OAuthToken twitterOAuthToken = getHomeModel().getHomeForm().getTwitterOAuthToken();
                    if (twitterOAuthToken == null) {
                        try {
                            LoginWithTwitter loginWithTwitter = new LoginWithTwitter(null);
                            loginWithTwitter.setHomeForm(getHomeModel().getHomeForm());
                            loginWithTwitter.login();

                            boolean processFurther = false;
                            while (!processFurther) {
                                if (LoginWithTwitter.deniedPermission)
                                    break;

                                twitterOAuthToken = getHomeModel().getHomeForm().getTwitterOAuthToken();
                                if (twitterOAuthToken == null) {
                                    Thread.sleep(10000);
                                } else {
                                    processFurther = true;
                                    isAlreadyLoggedIn = true;
                                }
                            }
                        } catch (IOException | InterruptedException ex) {
                            logger.error(ex);
                        }
                    }
                    if (!LoginWithTwitter.deniedPermission) {
                        Twitter twitter = new TwitterTemplate(SSNConstants.SSN_TWITTER_API_KEY,
                                SSNConstants.SSN_TWITTER_SECRET_KEY, twitterOAuthToken.getValue(),
                                twitterOAuthToken.getSecret());
                        TimelineOperations timelineOperations = twitter.timelineOperations();
                        if (!isAlreadyLoggedIn) {
                            SSNConfirmationDialogBox confirmeDialog = new SSNConfirmationDialogBox();
                            TwitterProfile userProfile = twitter.userOperations().getUserProfile();

                            String userName = "";
                            if (userProfile != null) {
                                userName = twitter.userOperations().getScreenName() != null
                                        ? twitter.userOperations().getScreenName()
                                        : userProfile.getName();
                            }
                            confirmeDialog.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(),
                                    "Confirmation", "",
                                    "You are already logged in with " + userName + ", Click OK to continue.");
                            int result = confirmeDialog.getResult();
                            if (result == JOptionPane.YES_OPTION) {
                                SwingUtilities.invokeLater(new Runnable() {
                                    public void run() {
                                        SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                                        messageDialogBox.initDialogBoxUI(
                                                SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Message", "",
                                                "Successfully uploaded.");
                                        messageDialogBox.setFocusable(true);

                                    }
                                });
                            } else if (result == JOptionPane.NO_OPTION) {

                                twitterOAuthToken = null;
                                if (twitterOAuthToken == null) {
                                    try {
                                        LoginWithTwitter loginWithTwitter = new LoginWithTwitter(null);
                                        loginWithTwitter.setHomeForm(getHomeModel().getHomeForm());
                                        loginWithTwitter.login();

                                        boolean processFurther = false;
                                        while (!processFurther) {
                                            twitterOAuthToken = getHomeModel().getHomeForm()
                                                    .getTwitterOAuthToken();
                                            if (twitterOAuthToken == null) {
                                                Thread.sleep(10000);
                                            } else {
                                                processFurther = true;

                                            }
                                        }
                                        twitter = new TwitterTemplate(SSNConstants.SSN_TWITTER_API_KEY,
                                                SSNConstants.SSN_TWITTER_SECRET_KEY,
                                                twitterOAuthToken.getValue(), twitterOAuthToken.getSecret());
                                        timelineOperations = twitter.timelineOperations();
                                    } catch (IOException | InterruptedException ex) {
                                        logger.error(ex);
                                    }
                                }
                            }
                        }

                        for (String file : sharedFileList) {
                            Resource image = new FileSystemResource(file);

                            TweetData tweetData = new TweetData("At " + new Date());
                            tweetData.withMedia(image);
                            timelineOperations.updateStatus(tweetData);
                        }
                    } else {
                        SSNMessageDialogBox messageDialogBox = new SSNMessageDialogBox();
                        messageDialogBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Alert",
                                "", "User denied for OurHive App permission on twitter.");
                        messageDialogBox.setFocusable(true);
                    }
                    getShareForm().dispose();
                }

            };
            thread.start();
            break;
        case "InstagramSharing":
            break;
        case "MailSharing":
            try {
                String OS = System.getProperty("os.name").toLowerCase();

                Set<String> sharedFileList = getFiles();
                Set<String> voiceNoteList = new HashSet<String>();
                for (String sharedFile : sharedFileList) {
                    String voiceNote = SSNDao.getVoiceCommandPath(new File(sharedFile).getAbsolutePath());
                    if (voiceNote != null && !voiceNote.isEmpty()) {
                        voiceNoteList.add(voiceNote);
                    }
                }
                sharedFileList.addAll(voiceNoteList);

                String fileFullPath = "";
                String caption = "";
                if (sharedFileList.size() == 1) {
                    fileFullPath = sharedFileList.toArray(new String[0])[0];

                    caption = SSMMediaGalleryPanel.readMetaDataForTitle(new File(fileFullPath));

                } else if (sharedFileList.size() > 1) {
                    fileFullPath = SSNHelper.createZipFileFromMultipleFiles(sharedFileList);
                }

                if (OS.contains("win")) {

                    // String subject = "SSN Subject";
                    String subject = caption.equals("") ? SSNConstants.SSN_SHARE_WITH_MAIL_SUBJECT : caption;
                    String body = "";
                    String m = "&subject=%s&body=%s";

                    String outLookExeDir = "C:\\Program Files\\Microsoft Office\\Office14\\Outlook.exe";
                    String mailCompose = "/c";
                    String note = "ipm.note";
                    String mailBodyContent = "/m";

                    m = String.format(m, subject, body);
                    String slashA = "/a";

                    String mailClientConfigParams[] = null;
                    Process startMailProcess = null;

                    mailClientConfigParams = new String[] { outLookExeDir, mailCompose, note, mailBodyContent,
                            m, slashA, fileFullPath };
                    startMailProcess = Runtime.getRuntime().exec(mailClientConfigParams);
                    OutputStream out = startMailProcess.getOutputStream();
                    File zipFile = new File(fileFullPath);
                    zipFile.deleteOnExit();
                } else if (OS.indexOf("mac") >= 0) {
                    //Process p = Runtime.getRuntime().exec(new String[]{String.format("open -a mail ", fileFullPath)});
                    Desktop desktop = Desktop.getDesktop();
                    String mailTo = caption.equals("") ? "?SUBJECT=" + SSNConstants.SSN_SHARE_WITH_MAIL_SUBJECT
                            : caption;
                    URI uriMailTo = null;
                    uriMailTo = new URI("mailto", mailTo, null);
                    desktop.mail(uriMailTo);
                }

                this.getShareForm().dispose();
            } catch (Exception ex) {
                logger.error(ex);
            }
            break;
        case "moveCopy":
            getShareForm().dispose();
            File album = new File(SSNHelper.getSsnHiveDirPath());
            File[] albumPaths = album.listFiles();
            Vector albumNames = new Vector();
            for (int i = 0; i < albumPaths.length; i++) {
                if (!(albumPaths[i].getName().equals("OurHive")) && SSNHelper.lastAlbum != null
                        && !(albumPaths[i].getName().equals(SSNHelper.lastAlbum)))
                    albumNames.add(albumPaths[i].getName());
            }
            if (SSNHelper.lastAlbum != null && !SSNHelper.lastAlbum.equals("OurHive"))
                albumNames.insertElementAt("OurHive", 0);

            SSNInputDialogBox inputBox = new SSNInputDialogBox(true, albumNames);
            inputBox.initDialogBoxUI(SSNDialogChoice.NOTIFICATION_DIALOG.getType(), "Copy Media",
                    "Please Select Album Name");
            String destAlbumName = inputBox.getTextValue();
            if (StringUtils.isNotBlank(destAlbumName)) {
                homeModel.moveAlbum(destAlbumName, getFiles());
            }

        }
        getShareForm().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
}

From source file:test.be.fedict.eid.applet.DesktopTest.java

@Test
public void mailto() throws Exception {
    Desktop desktop = Desktop.getDesktop();
    URI mailUri = new URI("mailto:frank.cornelis@fedict.be?subject="
            + URLEncoder.encode("Hello World", "UTF-8").replaceAll("\\+", "%20") + "&cc="
            + URLEncoder.encode("frank.cornelis@fedict.be", "UTF-8") + "&body="
            + URLEncoder.encode("test body message", "UTF-8").replaceAll("\\+", "%20"));
    LOG.debug("mail uri: " + mailUri);
    desktop.mail(mailUri);
}